diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6ea2445..91fdec1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -64,7 +64,7 @@ jobs: # we specify bash to get pipefail; it guards against the `curl` command # failing. otherwise `sh` won't catch that `curl` returned non-0 shell: bash - run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.32.0/cargo-dist-installer.sh | sh" + run: "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/axodotdev/cargo-dist/releases/download/v0.34.0/cargo-dist-installer.sh | sh" - name: Cache dist uses: actions/upload-artifact@v7 with: diff --git a/.gitignore b/.gitignore index 441fabe..b29f959 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,5 @@ target/ # MSVC Windows builds of rustc generate these, which store debugging information *.pdb -*.json *.session typos.toml diff --git a/.rot/known_issues.json b/.rot/known_issues.json new file mode 100644 index 0000000..19827bd --- /dev/null +++ b/.rot/known_issues.json @@ -0,0 +1,4 @@ +{ + "version": 1, + "issues": {} +} \ No newline at end of file diff --git a/.rot/snapshot.json b/.rot/snapshot.json new file mode 100644 index 0000000..57a933c --- /dev/null +++ b/.rot/snapshot.json @@ -0,0 +1,2356 @@ +{ + "version": 1, + "generated_at": 1794410560, + "entries": { + "src/main.rs|crate::main#free:b751b1361477": { + "kind": "Free", + "file": "src/main.rs", + "item_path": "crate::main#free:b751b1361477", + "comment_kind": "Line", + "comment_text": "// If RUST_LOG present, set debug else info log for this crate only", + "comment_hash": "b751b13614777ddfade5a86fcc8066d4bf42c55193aee716d40e25e7fe1e0c12", + "body_text": "if env::var(\"RUST_LOG\").is_ok() {} else {}\nlet working_path = data_local_dir();\nif let Some(location) = working_path {} else {}\n}", + "body_hash": "048d43daf8714f887fdcccd238705e5bf831c83d7d1def7de79d92bf3fde98a5" + }, + "src/telegram/backend.rs|crate::Backend": { + "kind": "Struct", + "file": "src/telegram/backend.rs", + "item_path": "crate::Backend", + "comment_kind": "OuterDoc", + "comment_text": " Everything on the Telegram side that the GUI talks to.\n", + "comment_hash": "c0d155a5cb04e381faadb16178d8b33bf2372d34bd162a96b045d8cf76b0446c", + "body_text": "pub struct Backend {\n runtime: Runtime,\n sink: EventSink,\n receiver: Receiver,\n clients: BTreeMap,\n pending: Option,\n cancel_scan: Arc,\n}", + "body_hash": "32ad64d8e8c0a24c6dd3cf1b0b252a213a9d94cd82e9a4655b8edc79a2d1194f" + }, + "src/telegram/backend.rs|crate::PendingLogin": { + "kind": "Struct", + "file": "src/telegram/backend.rs", + "item_path": "crate::PendingLogin", + "comment_kind": "OuterDoc", + "comment_text": " A login that is waiting for the user to finish it\n", + "comment_hash": "5d8b91723684c2508ec8054afdb08037cd3a3c8482b18a9f2cc5156b4e821cce", + "body_text": "struct PendingLogin {\n client: TGClient,\n code_token: Arc,\n password_token: Option,\n}", + "body_hash": "b21647af43c5c7dcd386e19b28de96ea1757c23317682dd748518d779012bdaf" + }, + "src/telegram/backend.rs|crate::impl Backend::cancel_login": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::cancel_login", + "comment_kind": "OuterDoc", + "comment_text": " Forget a login that was started but not finished\n", + "comment_hash": "1cd87c1d42f30481e7169d6bdc4ae7687d446297dadfc006b75ea05f2ddc47b9", + "body_text": "pub fn cancel_login(&mut self) {\n self.pending = None;\n }", + "body_hash": "1ab970ed75e6878dcdd0ff6e7c0faafe6de48c98023c777293343b3e0d775271" + }, + "src/telegram/backend.rs|crate::impl Backend::cancel_scan": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::cancel_scan", + "comment_kind": "OuterDoc", + "comment_text": " Ask the running count to stop at the next message\n", + "comment_hash": "69abb3aa00185c6ff27b7f1b59efa204e7b758a8884e28de965df0ff28231e8a", + "body_text": "pub fn cancel_scan(&self) {\n self.cancel_scan.store(true, Ordering::Release);\n }", + "body_hash": "4ccc3d99f7b585194af2c7559d33104c3fad6eaf0cc1b021c72ba40b780ed602" + }, + "src/telegram/backend.rs|crate::impl Backend::logout_temporary_sessions": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::logout_temporary_sessions", + "comment_kind": "OuterDoc", + "comment_text": " Log out of the sessions that were created as temporary and wait for it to finish\n", + "comment_hash": "35f1df79350733d8df873837ed73a6b573e8053281aec3a2d4aa9b6c8fef632e", + "body_text": "pub fn logout_temporary_sessions(&self) {\n let handles: Vec<_> = self\n .clients\n .values()\n .filter(|client| client.is_temporary())\n .cloned()\n .map(|client| self.runtime.spawn(async move { client.logout().await }))\n .collect();\n\n for handle in handles {\n let _ = self.runtime.block_on(handle);\n }\n }", + "body_hash": "f2e400aa82fc5f128a083529194d3f81f9ec105032b3ad7d9a739367d1b63e2f" + }, + "src/telegram/backend.rs|crate::impl Backend::poll": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::poll", + "comment_kind": "OuterDoc", + "comment_text": " Next event for the GUI, if any. State changes that come before it are applied first\n", + "comment_hash": "e0e23b811b4b8fe84bb3307f175af3eb6adbfa81633c04351cc3d792be6b6036", + "body_text": "pub fn poll(&mut self) -> Option {\n loop {\n match self.receiver.try_recv().ok()? {\n Packet::Event(event) => return Some(event),\n Packet::State(update) => self.apply(update),\n }\n }\n }", + "body_hash": "8c52e67ef41b8ce706e55d047e22c78c0c85a0db217c65cf252f8736cf5ca181" + }, + "src/telegram/backend.rs|crate::impl Backend::reset_cancel": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::reset_cancel", + "comment_kind": "OuterDoc", + "comment_text": " Must be called before a fresh scan, otherwise it would stop right away after a cancel\n", + "comment_hash": "72fd35d97ecbaa47667d7600211331ee6d55b735d0b81a1df86233fd8502f807", + "body_text": "pub fn reset_cancel(&self) {\n self.cancel_scan.store(false, Ordering::Relaxed);\n }", + "body_hash": "7f61c84ceac178b50f5bff18e68a741647f268e3eb3397ed3541a5ef5deec0c9" + }, + "src/telegram/backend.rs|crate::impl Backend::run": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::run", + "comment_kind": "OuterDoc", + "comment_text": " Runs a job and reports its error to the GUI\n", + "comment_hash": "388250847b11cb2831023da2358cba73e0385d4c1e507f0902936f16b739759e", + "body_text": "fn run(&self, task: impl Future> + Send + 'static) {\n let sink = self.sink.clone();\n\n self.runtime.spawn(async move {\n if let Err(err) = task.await {\n error!(\"Error acquired while handling a command: {err:?}\");\n sink.event(err);\n }\n });\n }", + "body_hash": "9923b8decd33da6992cc974eaa94cd55152f22b471ab70e74b4669fee57c4c3a" + }, + "src/telegram/backend.rs|crate::impl Backend::session_names": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::session_names", + "comment_kind": "OuterDoc", + "comment_text": " Names of the connected sessions in alphabetical order\n", + "comment_hash": "e3eb08b43823e9e409eca4b6b385188b1a721d15446798fce57025a091e7974b", + "body_text": "pub fn session_names(&self) -> Vec {\n self.clients.keys().cloned().collect()\n }", + "body_hash": "74e12eb770f5850230bf44d825b9df270f25d199e47291d15cf3d667f411a048" + }, + "src/telegram/backend.rs|crate::impl Backend::spawn": { + "kind": "Function", + "file": "src/telegram/backend.rs", + "item_path": "crate::impl Backend::spawn", + "comment_kind": "OuterDoc", + "comment_text": " Run any async job that does not report back through events\n", + "comment_hash": "37a3a3268a50f42db050f9f6b260dfbbb366b1afaceaa127fe504eee2aafe015", + "body_text": "pub fn spawn(&self, task: impl Future + Send + 'static) {\n self.runtime.spawn(task);\n }", + "body_hash": "2d39b049066251d64acc2fb43b283a6bb9ed13ba8efa8df0987cfc9f5570d502" + }, + "src/telegram/client.rs|crate::TGClient": { + "kind": "Struct", + "file": "src/telegram/client.rs", + "item_path": "crate::TGClient", + "comment_kind": "OuterDoc", + "comment_text": " A connected Telegram account. Created and kept by the [`Backend`]\n", + "comment_hash": "f56ef77cb9280180e1f75c33e8d1a7b59833c3d8cbf8793a4c4a0975048eb8aa", + "body_text": "#[derive(Clone)]\npub struct TGClient {\n client: Client,\n name: String,\n sink: EventSink,\n is_temporary: bool,\n}", + "body_hash": "231f29f5d6b8bd4502bfe19172302b79be1b203b06255f7605a5adc4bf852972" + }, + "src/telegram/client.rs|crate::impl TGClient::check_authorization": { + "kind": "Function", + "file": "src/telegram/client.rs", + "item_path": "crate::impl TGClient::check_authorization", + "comment_kind": "OuterDoc", + "comment_text": " Verifies if the current client is authorized for usage\n", + "comment_hash": "28b6d8a18ab27ea71f980d7093843945c1b5b90808a7b0be45ac3875e40e9643", + "body_text": "pub async fn check_authorization(&self) -> Result {\n let authorized: bool = self\n .client()\n .is_authorized()\n .await\n .map_err(ProcessError::UnknownError)?;\n\n info!(\"Client authorization status: {authorized}\");\n\n if !authorized {\n self.send(AccountEvent::Unauthorized(self.name()));\n return Ok(false);\n }\n\n Ok(true)\n }", + "body_hash": "1c48aedd675ccf34c8415c285415296faef7619474e5ea3634e836396c41757e" + }, + "src/telegram/client.rs|crate::impl TGClient::check_username": { + "kind": "Function", + "file": "src/telegram/client.rs", + "item_path": "crate::impl TGClient::check_username", + "comment_kind": "OuterDoc", + "comment_text": " Tries to resolve a username to get a Telegram chat account\n", + "comment_hash": "227019e68a7271c5df77fcb92837cecf908f46251167ec0c9a7155398f81885d", + "body_text": "pub async fn check_username(&self, chat_name: &str) -> Result {\n let tg_chat = self.client().resolve_username(chat_name).await;\n\n let Ok(tg_chat) = tg_chat else {\n error!(\"Failed to resolve username\");\n return Err(ProcessError::InvalidChat(chat_name.to_owned()));\n };\n\n let Some(tg_chat) = tg_chat else {\n error!(\"Found None value for target chat. Stopping processing\");\n return Err(ProcessError::InvalidChat(chat_name.to_owned()));\n };\n\n let name = tg_chat.name().unwrap_or(\"No name\");\n\n info!(\"Target chat {} exist\", name);\n\n Ok(tg_chat)\n }", + "body_hash": "fd24f69966022ecd40d10fe2456b3669a089c02044de5f936ecfed1e746c2c76" + }, + "src/telegram/client.rs|crate::impl TGClient::logout": { + "kind": "Function", + "file": "src/telegram/client.rs", + "item_path": "crate::impl TGClient::logout", + "comment_kind": "OuterDoc", + "comment_text": " Logs out of the client\n", + "comment_hash": "2db224a16be33a1d7b2ef7d711112a690d9b4a84589fac8c95261550af25d961", + "body_text": "pub async fn logout(&self) -> Result<(), ProcessError> {\n let _ = self.client().sign_out().await;\n info!(\"Logged out of client {}\", self.name());\n Ok(())\n }", + "body_hash": "1cbb473cacc089d53d4fb88188f1335c04f40ec80ae4514bd7028a72c32ac173" + }, + "src/telegram/client.rs|crate::impl TGClient::send": { + "kind": "Function", + "file": "src/telegram/client.rs", + "item_path": "crate::impl TGClient::send", + "comment_kind": "OuterDoc", + "comment_text": " Tell the GUI something happened\n", + "comment_hash": "059c5bd16f8ff03a022a3dc0a01e28e097fa577c1a44e8a851857cdf890e8ced", + "body_text": "pub fn send(&self, event: impl Into) {\n self.sink.event(event);\n }", + "body_hash": "af4f9eba2733b48582cec1b5820e719754a5b4f60532c9903fe1b74b62e36758" + }, + "src/telegram/commands.rs|crate::Command": { + "kind": "Enum", + "file": "src/telegram/commands.rs", + "item_path": "crate::Command", + "comment_kind": "OuterDoc", + "comment_text": " Everything the GUI can ask the Telegram side to do. Sent through [`Backend::send`]\n", + "comment_hash": "21e7196420af402296346065c642bb00626bcf24e1a1eb0aef05b05eeedfc204", + "body_text": "pub enum Command {\n ConnectSavedSessions(Vec),\n RefreshSessions {\n new_files: Vec,\n },\n RequestLoginCode {\n session: String,\n phone: String,\n temporary: bool,\n },\n SubmitLoginCode {\n code: String,\n },\n SubmitPassword {\n password: String,\n },\n CheckChat {\n session: String,\n chat: String,\n start: Option,\n end: Option,\n },\n StartCount {\n session: String,\n chat: String,\n start: Option,\n end: Option,\n multi_session: bool,\n },\n LoadWhitelist {\n session: String,\n peers: Vec,\n },\n AddWhitelistUser {\n session: String,\n username: String,\n },\n LoadBlacklist {\n session: String,\n peers: Vec,\n },\n AddBlacklistUser {\n session: String,\n username: String,\n },\n}", + "body_hash": "ff1ddf179f3e6be5512c807fca47e8916f9028cf08fcc10d9cbd273b3af507a8" + }, + "src/telegram/commands.rs|crate::Command::CheckChat": { + "kind": "Variant", + "file": "src/telegram/commands.rs", + "item_path": "crate::Command::CheckChat", + "comment_kind": "OuterDoc", + "comment_text": " Check that the chat exists and find the range to count\n\n Verify every session still works, drop the ones that do not, then check the chat\n\n with `session` (or another working one if it was dropped)\n", + "comment_hash": "3dcd25343d9521b6747df62b2c17a56c2372183eff414a2779a77d1d569a1d2b", + "body_text": "CheckChat {\n session: String,\n chat: String,\n start: Option,\n end: Option,\n }", + "body_hash": "766a481c8cf9231f4df6e0e4bafd6d8c2dae4d9d176ef54a87debb0926edb363" + }, + "src/telegram/commands.rs|crate::Command::ConnectSavedSessions": { + "kind": "Variant", + "file": "src/telegram/commands.rs", + "item_path": "crate::Command::ConnectSavedSessions", + "comment_kind": "OuterDoc", + "comment_text": " Connect to the saved session files and keep the ones that are still logged in\n", + "comment_hash": "bb33efaa61c685d6ade4352e9b9ad6445de29320aa6eb95da6708ff54bc87f14", + "body_text": "ConnectSavedSessions(Vec)", + "body_hash": "5236e2c70f5b5da0abfe99d9be262ad499f4a9bfb87f226f50c23396d39b569e" + }, + "src/telegram/commands.rs|crate::Command::RefreshSessions": { + "kind": "Variant", + "file": "src/telegram/commands.rs", + "item_path": "crate::Command::RefreshSessions", + "comment_kind": "OuterDoc", + "comment_text": " Drop sessions that got logged out and connect the given saved sessions\n", + "comment_hash": "4f8e1ddfa97421906894a258240fff1347b44a3e21cd8700af9c0d4ff7b52ace", + "body_text": "RefreshSessions {\n new_files: Vec,\n }", + "body_hash": "8e86132d720d12dc5263c766ddebfd623736737b5bee05ba580174e8a3f4f519" + }, + "src/telegram/commands.rs|crate::Command::SubmitLoginCode": { + "kind": "Variant", + "file": "src/telegram/commands.rs", + "item_path": "crate::Command::SubmitLoginCode", + "comment_kind": "OuterDoc", + "comment_text": " Finish the login that is waiting for a code\n", + "comment_hash": "4d62a2b92fefe31ef1e0aade751f60aa7aef5258856c9ff2d0a7a47761694fe9", + "body_text": "SubmitLoginCode {\n code: String,\n }", + "body_hash": "47bdc5d88e15488a3461f909be4cd70805acf88b7a2665ffa50b0d6e90a6baf4" + }, + "src/telegram/commands.rs|crate::Command::SubmitPassword": { + "kind": "Variant", + "file": "src/telegram/commands.rs", + "item_path": "crate::Command::SubmitPassword", + "comment_kind": "OuterDoc", + "comment_text": " Finish the login that is waiting for the two-step verification password\n", + "comment_hash": "5a017f42524dfd56f73c944e0fba3c258f5e42b689bed84c45325f329bfbe97b", + "body_text": "SubmitPassword {\n password: String,\n }", + "body_hash": "2f3cedcdb14b31887cac41ac7e012798ed6d01bca5b708775801197e97ac8a9b" + }, + "src/telegram/events.rs|crate::AccountEvent::SessionsDropped": { + "kind": "Variant", + "file": "src/telegram/events.rs", + "item_path": "crate::AccountEvent::SessionsDropped", + "comment_kind": "OuterDoc", + "comment_text": " Sessions that are no longer logged in and were removed\n", + "comment_hash": "f87c85229cc01c4f553b87d083fac9e77d6f2c95ffb01cb3aac2165477299464", + "body_text": "SessionsDropped(Vec)", + "body_hash": "8295ba12070f0c87f950df942439cfd54401377aecbc41cffbdebda0d921ef26" + }, + "src/telegram/events.rs|crate::AccountEvent::SessionsRefreshed": { + "kind": "Variant", + "file": "src/telegram/events.rs", + "item_path": "crate::AccountEvent::SessionsRefreshed", + "comment_kind": "OuterDoc", + "comment_text": " A refresh finished without any new session to connect\n", + "comment_hash": "f313383cf5697adf53d030ccda3efb5a77668fefaf3bc23a3b08ed88b59908fd", + "body_text": "SessionsRefreshed {\n working: usize,\n }", + "body_hash": "5dc6b41c50eb3f569f153726f0b4336c28028307ad2b515f3bce5e9f80911094" + }, + "src/telegram/events.rs|crate::Event": { + "kind": "Enum", + "file": "src/telegram/events.rs", + "item_path": "crate::Event", + "comment_kind": "OuterDoc", + "comment_text": " Everything the Telegram side can tell the GUI, grouped by topic\n", + "comment_hash": "16f02169dce746b9c7b54c51a6910656b3e3861c3fdfea2ca824d5d2cac4c61d", + "body_text": "pub enum Event {\n Account(AccountEvent),\n Scan(ScanEvent),\n Users(UsersEvent),\n Failed(ProcessError),\n}", + "body_hash": "46b842cea155a6bdf8346ee67ca0ed3b08a95f2bf84df4a2734f4646c536853f" + }, + "src/telegram/events.rs|crate::EventSink": { + "kind": "Struct", + "file": "src/telegram/events.rs", + "item_path": "crate::EventSink", + "comment_kind": "OuterDoc", + "comment_text": " The only way for async code to reach the GUI. Wakes the GUI up after every message\n", + "comment_hash": "8325f157499ae7460983fd5cc9da8be7f786342301770434f864571de3052340", + "body_text": "#[derive(Clone)]\npub struct EventSink {\n sender: Sender,\n context: Context,\n}", + "body_hash": "34a80b0e10139998141ca73384db5b643f4f783e89179a4e68e620bda342cbdf" + }, + "src/telegram/events.rs|crate::ProcessError::NoUsableSession": { + "kind": "Variant", + "file": "src/telegram/events.rs", + "item_path": "crate::ProcessError::NoUsableSession", + "comment_kind": "OuterDoc", + "comment_text": " Every session was logged out or unreachable\n", + "comment_hash": "3b4ffe92ef1f4c6fd5ba2f5d686edfcb46236c1a6d4b8d6fc47c417e238daf52", + "body_text": "NoUsableSession", + "body_hash": "165d8b739328e5825fb63a388e23cc0b56a2e1c2d0886ec87b6099deea3c810a" + }, + "src/telegram/events.rs|crate::ScanEvent::ChatChecked": { + "kind": "Variant", + "file": "src/telegram/events.rs", + "item_path": "crate::ScanEvent::ChatChecked", + "comment_kind": "OuterDoc", + "comment_text": " The chat exists, this is the message range to count\n", + "comment_hash": "920ff82e5e005682421ff8b6f626547fa90ec600dc592c510ad827d5a3be975a", + "body_text": "ChatChecked {\n chat: String,\n start: i32,\n end: i32,\n sessions: Vec,\n }", + "body_hash": "b4930c05342e88c8abf03b1416978cc0683f0ea83c519e834e668cbb9e6ad447" + }, + "src/telegram/events.rs|crate::ScanEvent::ChatChecked::sessions": { + "kind": "Field", + "file": "src/telegram/events.rs", + "item_path": "crate::ScanEvent::ChatChecked::sessions", + "comment_kind": "OuterDoc", + "comment_text": " The sessions that passed the check and can share the work\n", + "comment_hash": "444b262553352380be1b19867a78bae9434799740a6a0101bb3e95f106fd428d", + "body_text": "sessions: Vec", + "body_hash": "ce6e0c2b50927288c13a63fdac9466d122472dfab9e80ff9d128e7b117214861" + }, + "src/telegram/scan.rs|crate::check_scan_sessions": { + "kind": "Function", + "file": "src/telegram/scan.rs", + "item_path": "crate::check_scan_sessions", + "comment_kind": "OuterDoc", + "comment_text": " Checks that every session is still logged in before work is shared between them, then\n\n checks the chat with the preferred session, or the first working one if that was dropped\n", + "comment_hash": "73b7c5c390ddf7e5ace9f2967c4030f507c8528860712ec0b618e49ac8447af3", + "body_text": "pub async fn check_scan_sessions(\n clients: Vec,\n preferred: String,\n chat: String,\n start: Option,\n end: Option,\n) -> Result<(), ProcessError> {\n let usable = verify_sessions(clients).await;\n\n let Some(checker) = usable\n .iter()\n .find(|client| client.name() == preferred)\n .or(usable.first())\n .cloned()\n else {\n return Err(ProcessError::NoUsableSession);\n };\n\n let names = usable.iter().map(TGClient::name).collect();\n checker.check_chat_status(chat, start, end, names).await\n}", + "body_hash": "1a635627fb250ee1a41b5bec675f01fff8e4f7443e2aff19b35e4865c040634b" + }, + "src/telegram/scan.rs|crate::impl TGClient::start_count": { + "kind": "Function", + "file": "src/telegram/scan.rs", + "item_path": "crate::impl TGClient::start_count", + "comment_kind": "OuterDoc", + "comment_text": " Iters through a Telegram chat from a given point to the first message or until the end point is reached\n", + "comment_hash": "22d954e3e25ac65306021cd7b427044ffb20847820d1ef2e3ce2a2c35fffbe44", + "body_text": "pub async fn start_count(\n &self,\n start_chat: String,\n start_num: Option,\n end_num: Option,\n multi_session: bool,\n cancel: Arc,\n ) -> Result<(), ProcessError> {\n if !self.check_authorization().await? {\n return Ok(());\n }\n\n let tg_chat = self.check_username(&start_chat).await?;\n\n info!(\n \"{} exists. Starting iterating messages\",\n tg_chat.name().unwrap_or(\"No Name\")\n );\n\n let end_at = end_num.unwrap_or(1);\n let mut start_at = start_num.unwrap_or(-1);\n\n info!(\"Starting message num {start_at}, ending message num {end_at}\");\n\n let last_sent = Arc::new(Mutex::new(Some(Instant::now())));\n\n let last_sent_clone = last_sent.clone();\n let sink = self.sink().clone();\n\n \n \n thread::spawn(move || {\n loop {\n sleep(Duration::from_millis(500));\n\n let last_sent = last_sent_clone.lock().unwrap();\n\n if let Some(last_sent) = *last_sent {\n let time_passed = last_sent.elapsed().as_millis();\n if time_passed > 500 && time_passed < 1050 {\n sink.event(ScanEvent::FloodWait);\n }\n\n \n if time_passed > 60000 {\n break;\n }\n } else {\n break;\n }\n }\n });\n\n let mut last_number = -1;\n\n let peer_ref = tg_chat.to_ref().await;\n\n let Ok(peer_ref) = peer_ref else {\n return Err(ProcessError::FailedLatestMessage);\n };\n\n let Some(peer_ref) = peer_ref else {\n return Err(ProcessError::FailedLatestMessage);\n };\n\n let mut iter_message = self.client().iter_messages(peer_ref);\n\n \n \n \n if start_at != -1 {\n iter_message = iter_message.offset_id(start_at + 1);\n last_number = start_at + 1;\n }\n\n while let Some(message) = iter_message\n .next()\n .await\n .map_err(ProcessError::UnknownError)?\n {\n let message_num = message.id();\n if start_at == -1 {\n info!(\"Setting starting point as {message_num}\");\n start_at = message_num;\n }\n\n let cancelled = cancel.load(Ordering::Acquire);\n if message_num < end_at || cancelled {\n break;\n }\n\n if message_num <= start_at {\n \n let sender_ref = match message.sender() {\n Some(sender) => sender.to_ref().await.ok().flatten(),\n None => None,\n };\n\n let count_data = TGCountData::new(\n self.name(),\n message,\n sender_ref,\n start_at,\n end_at,\n last_number,\n multi_session,\n );\n\n self.send(ScanEvent::Message(Box::new(count_data)));\n last_number = message_num;\n }\n\n \n if start_at - end_at > 3000 {\n sleep(Duration::from_millis(5));\n } else {\n sleep(Duration::from_millis(2));\n }\n\n {\n let mut last_sent_lock = last_sent.lock().unwrap();\n *last_sent_lock = Some(Instant::now());\n }\n }\n\n let mut last_sent_lock = last_sent.lock().unwrap();\n *last_sent_lock = None;\n\n self.send(ScanEvent::Finished {\n end_at,\n last_number,\n });\n\n Ok(())\n }", + "body_hash": "d112dd850fa6738050c77b423d5615c937faa7f99cdddc91d875d0b01d2c37ab" + }, + "src/telegram/scan.rs|crate::impl TGClient::start_count#free:0c79054e36ff": { + "kind": "Free", + "file": "src/telegram/scan.rs", + "item_path": "crate::impl TGClient::start_count#free:0c79054e36ff", + "comment_kind": "Line", + "comment_text": "// stop this thread if no activity for over 60 seconds", + "comment_hash": "0c79054e36ff843f01e7d818c18cb71735b2d97a0266f409de6e02d52a512be1", + "body_text": "if time_passed > 60000 {}\n}", + "body_hash": "b9eb30af701245704a37c370af8782fd745b7d4fedad4748cc1f0d5df2cd0d17" + }, + "src/telegram/scan.rs|crate::impl TGClient::start_count#free:1b4bafce862c": { + "kind": "Free", + "file": "src/telegram/scan.rs", + "item_path": "crate::impl TGClient::start_count#free:1b4bafce862c", + "comment_kind": "Line", + "comment_text": "// Sleep to prevent flood time being too noticeable/getting triggered", + "comment_hash": "1b4bafce862c5ceadb91e52dce9fb2686897b4f455bc92abb342d572827f5b46", + "body_text": "if start_at - end_at > 3000 {} else {}\n{}\n}", + "body_hash": "6db636f6fb870b098373b7f1510a1a5319d7d1f7450b8fb7a29f2063e9837373" + }, + "src/telegram/scan.rs|crate::impl TGClient::start_count#free:71e9afb9fb77": { + "kind": "Free", + "file": "src/telegram/scan.rs", + "item_path": "crate::impl TGClient::start_count#free:71e9afb9fb77", + "comment_kind": "Line", + "comment_text": "// Every 500 ms, check when the last communication was made with the GUI.\n// If over 500, let the GUI side know that a flood wait was triggered", + "comment_hash": "71e9afb9fb77a324499ef99d947a8c38d92a657f406545a7676ebd4afcb78498", + "body_text": "thread::spawn(move || {});\nlet mut last_number = -1;\nlet peer_ref = tg_chat.to_ref().await;\nlet Ok(peer_ref) = peer_ref else {};\nlet Some(peer_ref) = peer_ref else {};\nlet mut iter_message = self.client().iter_messages(peer_ref);", + "body_hash": "8919d2b81a9275c7cb20e5b674cb9a81c390388a32a2d821d180cd6f57827e1a" + }, + "src/telegram/scan.rs|crate::impl TGClient::start_count#free:723bc9c77c05": { + "kind": "Free", + "file": "src/telegram/scan.rs", + "item_path": "crate::impl TGClient::start_count#free:723bc9c77c05", + "comment_kind": "Line", + "comment_text": "// Add 1 to offset because the latest message would start from the offset point - 1 message\n// Add 1 to last_number if the starting message is 100 but does not exist and starts from 99, we want to count that missing message\n// If last_number is 100, it would be counted as normal message progression", + "comment_hash": "723bc9c77c05a6033cb64c1d7504a813157d6140a30336679ecfcaa099f824cd", + "body_text": "if start_at != -1 {}\nwhile let Some(message) = iter_message\n .next()\n .await\n .map_err(ProcessError::UnknownError)?\n {}\nlet mut last_sent_lock = last_sent.lock().unwrap();\n*last_sent_lock = None;\nself.send(ScanEvent::Finished {\n end_at,\n last_number,\n });\nOk(())\n}", + "body_hash": "2baa5e94f0bea6500ec972b6a1ac9be55a27088c7b8d540816a71417a4e1a643" + }, + "src/telegram/scan.rs|crate::impl TGClient::start_count#free:9d545ae81e46": { + "kind": "Free", + "file": "src/telegram/scan.rs", + "item_path": "crate::impl TGClient::start_count#free:9d545ae81e46", + "comment_kind": "Line", + "comment_text": "// Only possible to get a reference if the sender is usable or cached in the session", + "comment_hash": "9d545ae81e46e88550d7182b0f8017ff5c17edc744533b277d013a5118dbcf2d", + "body_text": "let sender_ref = match message.sender() {\n Some(sender) => sender.to_ref().await.ok().flatten(),\n None => None,\n };\nlet count_data = TGCountData::new(\n self.name(),\n message,\n sender_ref,\n start_at,\n end_at,\n last_number,\n multi_session,\n );\nself.send(ScanEvent::Message(Box::new(count_data)));\nlast_number = message_num;\n}", + "body_hash": "37361634ca063cf78377920c1078589884b05cd3da89131c8453ec1644723828" + }, + "src/telegram/sessions/new.rs|crate::impl TGClient::sign_in_code": { + "kind": "Function", + "file": "src/telegram/sessions/new.rs", + "item_path": "crate::impl TGClient::sign_in_code", + "comment_kind": "OuterDoc", + "comment_text": " Tries to sign in to a Telegram account with the given Telegram login code\n", + "comment_hash": "0c0665be87dc66e5b6a18343fb40a329e4c7429c174da027606edf85d8b69ba2", + "body_text": "pub async fn sign_in_code(\n &self,\n token: Arc,\n code: String,\n ) -> Result<(), ProcessError> {\n let result = self.client().sign_in(&token, &code).await;\n\n match result {\n Ok(_) => {\n self.finish_login();\n }\n Err(err) => match err {\n SignInError::InvalidCode => self.send(ProcessError::InvalidTGCode),\n SignInError::PasswordRequired(token) => {\n self.sink().state(StateUpdate::PasswordRequired(token));\n self.send(AccountEvent::PasswordRequired);\n }\n SignInError::SignUpRequired => self.send(ProcessError::NotSignedUp),\n SignInError::InvalidPassword(_) => unreachable!(),\n SignInError::Other(e) => self.send(ProcessError::UnknownError(e)),\n },\n }\n Ok(())\n }", + "body_hash": "d0b6aad375a58267dd3a2d57a0d158ec97ea030de62e8672179f260d394c6327" + }, + "src/telegram/sessions/new.rs|crate::impl TGClient::sign_in_password": { + "kind": "Function", + "file": "src/telegram/sessions/new.rs", + "item_path": "crate::impl TGClient::sign_in_password", + "comment_kind": "OuterDoc", + "comment_text": " Tries to sign in to a Telegram account with the given login password.\n\n May continue to fail if the first time password was not correct\n", + "comment_hash": "62e0d6e8d94f6b325b19ce19202a602e4184ecb9671769cf3cef431a4154ab16", + "body_text": "pub async fn sign_in_password(\n &self,\n token: PasswordToken,\n password: String,\n ) -> Result<(), ProcessError> {\n let result = self.client().check_password(token, password).await;\n\n match result {\n Ok(_) => {\n self.finish_login();\n }\n Err(err) => match err {\n SignInError::InvalidCode\n | SignInError::PasswordRequired(_)\n | SignInError::SignUpRequired => unreachable!(),\n SignInError::InvalidPassword(new_token) => {\n self.sink().state(StateUpdate::PasswordRejected(new_token));\n self.send(ProcessError::InvalidPassword);\n }\n SignInError::Other(e) => self.send(ProcessError::UnknownError(e)),\n },\n }\n\n Ok(())\n }", + "body_hash": "926f4a58168efe14a098332905c26c4461ee63387079bb07e253449d9e87dba1" + }, + "src/telegram/sessions/new.rs|crate::send_login_code": { + "kind": "Function", + "file": "src/telegram/sessions/new.rs", + "item_path": "crate::send_login_code", + "comment_kind": "OuterDoc", + "comment_text": " Tries to send Telegram login code to the given phone number\n", + "comment_hash": "a4b1f8698d6dc24f5eca252281862fd54a97ff833256d42ffa1f9ef3338243ab", + "body_text": "pub async fn send_login_code(\n sink: EventSink,\n session_name: String,\n phone_number: String,\n is_temporary: bool,\n) -> Result<(), ProcessError> {\n let Some(api_data) = get_api_keys() else {\n error!(\"No API keys found\");\n return Err(ProcessError::InvalidAPIKeys);\n };\n\n let Ok(api_id) = api_data.api_id.parse() else {\n error!(\"Failed to parse API ID. Given API ID: {}\", api_data.api_id);\n return Err(ProcessError::InvalidAPIKeys);\n };\n let api_hash = api_data.api_hash;\n\n let pool = if is_temporary {\n let session = Arc::new(MemorySession::default());\n SenderPool::new(Arc::clone(&session), api_id)\n } else {\n let target_path = format!(\"{session_name}.sqlite\");\n\n if fs::metadata(&target_path).is_ok() {\n info!(\"{target_path} exists. Removing old sqlite file\");\n fs::remove_file(&target_path).expect(\"Failed to remove old sqlite file\");\n }\n\n let session = SqliteSession::open(target_path).await;\n\n if let Err(e) = session {\n error!(\"Failed to create/open session file: {e}\");\n return Err(ProcessError::FileCreationError);\n }\n\n let session = Arc::new(session.unwrap());\n\n SenderPool::new(Arc::clone(&session), api_id)\n };\n\n let SenderPool { runner, handle, .. } = pool;\n tokio::spawn(runner.run());\n\n let client = Client::new(handle);\n\n let code_token = client\n .request_login_code(&phone_number, &api_hash)\n .await\n .map_err(ProcessError::InvalidPhoneOrAPI)?;\n\n let new_client = TGClient::new(client, session_name, sink.clone(), is_temporary);\n\n sink.state(StateUpdate::LoginCodeSent {\n client: new_client,\n token: code_token,\n });\n\n sink.event(AccountEvent::LoginCodeSent);\n\n Ok(())\n}", + "body_hash": "65251ad9b148ff30cfc5ac5e2694f9bbc9f2e5553f8c6ad93c564ff7c9ddc6bc" + }, + "src/telegram/sessions/restore.rs|crate::connect_to_session": { + "kind": "Function", + "file": "src/telegram/sessions/restore.rs", + "item_path": "crate::connect_to_session", + "comment_kind": "OuterDoc", + "comment_text": " Tries to establish a connection to the local Telegram sqlite files\n", + "comment_hash": "ca3979d455adace9bb06520881d1edb6f9450520cfc96b27014279ec28d998c7", + "body_text": "pub async fn connect_to_session(sink: EventSink, names: Vec) -> Result<(), ProcessError> {\n let Some(api_data) = get_api_keys() else {\n error!(\"No API keys found\");\n return Err(ProcessError::InvalidAPIKeys);\n };\n\n let Ok(api_id) = api_data.api_id.parse() else {\n error!(\"Failed to parse API ID. Given API ID: {}\", api_data.api_id);\n return Err(ProcessError::InvalidAPIKeys);\n };\n\n let mut successful_session = Vec::new();\n let mut failed_session = Vec::new();\n\n let mut all_clients = Vec::new();\n\n for name in names {\n let name_without_sqlite = name.replace(\".sqlite\", \"\");\n\n let session = SqliteSession::open(name).await;\n\n if let Err(e) = session {\n error!(\"Failed to open session file: {e}\");\n failed_session.push(name_without_sqlite);\n continue;\n }\n\n let session = Arc::new(session.unwrap());\n\n let SenderPool { runner, handle, .. } = SenderPool::new(Arc::clone(&session), api_id);\n tokio::spawn(runner.run());\n\n let client = Client::new(handle);\n\n info!(\"Connected to Session {name_without_sqlite} successfully\");\n\n let authorized = client.is_authorized().await;\n\n let Ok(authorized) = authorized else {\n info!(\"Failed to determine session authorization status {name_without_sqlite}\");\n failed_session.push(name_without_sqlite);\n continue;\n };\n\n info!(\"Session {name_without_sqlite} authorization status: {authorized}\");\n\n if !authorized {\n failed_session.push(name_without_sqlite);\n continue;\n }\n\n let new_client = TGClient::new(client, name_without_sqlite.clone(), sink.clone(), false);\n all_clients.push(new_client);\n successful_session.push(name_without_sqlite);\n }\n\n sink.state(StateUpdate::ClientsRestored(all_clients));\n sink.event(AccountEvent::SessionsRestored {\n connected: successful_session,\n failed: failed_session,\n });\n\n Ok(())\n}", + "body_hash": "c3eae4fedef1042e14e445afe6e8fec748c1e69b79bd0161c4a7750ca017439a" + }, + "src/telegram/sessions/verify.rs|crate::refresh_sessions": { + "kind": "Function", + "file": "src/telegram/sessions/verify.rs", + "item_path": "crate::refresh_sessions", + "comment_kind": "OuterDoc", + "comment_text": " Drops sessions that got logged out and connects to saved sessions that are not connected yet\n", + "comment_hash": "7edd67e51ed5de91dad34a7ace26e56b0299b8d9c06fa37561cbad4befdf8a6b", + "body_text": "pub async fn refresh_sessions(\n sink: EventSink,\n clients: Vec,\n new_files: Vec,\n) -> Result<(), ProcessError> {\n let working = verify_sessions(clients).await.len();\n\n if new_files.is_empty() {\n sink.event(AccountEvent::SessionsRefreshed { working });\n return Ok(());\n }\n\n connect_to_session(sink, new_files).await\n}", + "body_hash": "2a1a05222b8805e6ec7bb79a6520ff5b7b92b396fdeaf2c10797125982d0706f" + }, + "src/telegram/sessions/verify.rs|crate::verify_sessions": { + "kind": "Function", + "file": "src/telegram/sessions/verify.rs", + "item_path": "crate::verify_sessions", + "comment_kind": "OuterDoc", + "comment_text": " Returns the sessions that are still logged in.\n\n\n\n Sessions that were logged out since they connected are removed from the backend and\n\n reported to the GUI. Sessions that could not be reached are only left out of the result\n\n and stay connected.\n", + "comment_hash": "217582d36089fa5e6a7a9ae98b26106d3ab4d6f1b13301a84ffb621871b0b75e", + "body_text": "pub async fn verify_sessions(clients: Vec) -> Vec {\n let Some(sink) = clients.first().map(|client| client.sink().clone()) else {\n return Vec::new();\n };\n\n let mut usable = Vec::new();\n let mut dropped = Vec::new();\n\n for client in clients {\n match client.client().is_authorized().await {\n Ok(true) => usable.push(client),\n Ok(false) => {\n info!(\n \"Session {} is no longer logged in. Dropping it\",\n client.name()\n );\n dropped.push(client.name());\n }\n Err(e) => {\n error!(\n \"Could not check session {}, skipping it for now: {e}\",\n client.name()\n );\n }\n }\n }\n\n if !dropped.is_empty() {\n sink.state(StateUpdate::SessionsDropped(dropped.clone()));\n sink.event(AccountEvent::SessionsDropped(dropped));\n }\n\n usable\n}", + "body_hash": "da4a2edc903a2b5e67582651d3e914be3abdac83602feda972689883caed9fc1" + }, + "src/telegram/users/blacklist.rs|crate::impl TGClient::load_blacklisted_users": { + "kind": "Function", + "file": "src/telegram/users/blacklist.rs", + "item_path": "crate::impl TGClient::load_blacklisted_users", + "comment_kind": "OuterDoc", + "comment_text": " Resolves saved `PeerRef` values and sends them to the GUI\n", + "comment_hash": "8bd5a76a3f14fa2dff6bcf1d7f24e700f3817188f669a32468b480ea7f13bc09", + "body_text": "pub async fn load_blacklisted_users(\n &self,\n peer_refs: Vec,\n ) -> Result<(), ProcessError> {\n info!(\"Starting resolving peers by {}\", self.name());\n let mut peer_list = Vec::new();\n let mut failed_peer_num = 0;\n\n for peer_ref in peer_refs {\n match self.client().resolve_peer(peer_ref).await {\n Ok(peer) => {\n peer_list.push(UnpackedBlacklistedUser::new(&peer, peer_ref, self.name()))\n }\n Err(e) => {\n error!(\"Failed to resolve a peer. Error: {e}\");\n failed_peer_num += 1;\n }\n }\n }\n\n self.send(UsersEvent::BlacklistLoaded {\n users: peer_list,\n failed: failed_peer_num,\n });\n\n Ok(())\n }", + "body_hash": "3c6ee2e3148926284e888d5f3752ceb5a08648ac316625ac0bdb3ade1ad1e900" + }, + "src/telegram/users/blacklist.rs|crate::impl TGClient::new_blacklist": { + "kind": "Function", + "file": "src/telegram/users/blacklist.rs", + "item_path": "crate::impl TGClient::new_blacklist", + "comment_kind": "OuterDoc", + "comment_text": " Tries to get a Telegram chat with the given chat name\n", + "comment_hash": "aa41273c08e4a7e43966e13228bf79ed335a82eab8f8dff7f33f413c7020714e", + "body_text": "pub async fn new_blacklist(&self, chat_name: String) -> Result<(), ProcessError> {\n if !self.check_authorization().await? {\n return Ok(());\n }\n\n let tg_chat = self.check_username(&chat_name).await?;\n\n let peer_ref = match tg_chat.to_ref().await {\n Ok(Some(peer_ref)) => peer_ref,\n _ => {\n error!(\"Failed to get a reference of the peer\");\n return Err(ProcessError::InvalidChat(chat_name));\n }\n };\n\n self.send(UsersEvent::BlacklistAdded(Box::new(\n UnpackedBlacklistedUser::new(&tg_chat, peer_ref, self.name()),\n )));\n\n Ok(())\n }", + "body_hash": "7ef90399ecee055b51793ef09caa12cd6a908bc66d42e42e48ab76f7e593366e" + }, + "src/telegram/users/whitelist.rs|crate::impl TGClient::load_whitelisted_users": { + "kind": "Function", + "file": "src/telegram/users/whitelist.rs", + "item_path": "crate::impl TGClient::load_whitelisted_users", + "comment_kind": "OuterDoc", + "comment_text": " Resolves saved `PeerRef` values and sends them to the GUI\n", + "comment_hash": "8bd5a76a3f14fa2dff6bcf1d7f24e700f3817188f669a32468b480ea7f13bc09", + "body_text": "pub async fn load_whitelisted_users(\n &self,\n peer_refs: Vec,\n ) -> Result<(), ProcessError> {\n info!(\"Starting resolving peers by {}\", self.name());\n let mut peer_list = Vec::new();\n let mut failed_peer_num = 0;\n\n for peer_ref in peer_refs {\n match self.client().resolve_peer(peer_ref).await {\n Ok(peer) => {\n peer_list.push(UnpackedWhitelistedUser::new(&peer, peer_ref, self.name()))\n }\n Err(e) => {\n error!(\"Failed to resolve a peer. Error: {e}\");\n failed_peer_num += 1;\n }\n }\n }\n\n self.send(UsersEvent::WhitelistLoaded {\n users: peer_list,\n failed: failed_peer_num,\n });\n\n Ok(())\n }", + "body_hash": "ff9b3fb54301be5f6decffc8fc7296207d6409418499711caeed29fb9ae6c139" + }, + "src/telegram/users/whitelist.rs|crate::impl TGClient::new_whitelist": { + "kind": "Function", + "file": "src/telegram/users/whitelist.rs", + "item_path": "crate::impl TGClient::new_whitelist", + "comment_kind": "OuterDoc", + "comment_text": " Tries to get a Telegram chat with the given chat name\n", + "comment_hash": "aa41273c08e4a7e43966e13228bf79ed335a82eab8f8dff7f33f413c7020714e", + "body_text": "pub async fn new_whitelist(&self, chat_name: String) -> Result<(), ProcessError> {\n if !self.check_authorization().await? {\n return Ok(());\n }\n\n let tg_chat = self.check_username(&chat_name).await?;\n\n let peer_ref = match tg_chat.to_ref().await {\n Ok(Some(peer_ref)) => peer_ref,\n _ => {\n error!(\"Failed to get a reference of the peer\");\n return Err(ProcessError::InvalidChat(chat_name));\n }\n };\n\n self.send(UsersEvent::WhitelistAdded(Box::new(\n UnpackedWhitelistedUser::new(&tg_chat, peer_ref, self.name()),\n )));\n\n Ok(())\n }", + "body_hash": "a0385d0042330ee46ec146a28e8c8564fc75bbb9983e1603d385d49bb23e5b9c" + }, + "src/ui/api_keys.rs|crate::field_error": { + "kind": "Function", + "file": "src/ui/api_keys.rs", + "item_path": "crate::field_error", + "comment_kind": "OuterDoc", + "comment_text": " Small red hint under a field, takes no space when there is nothing to say\n", + "comment_hash": "3f98f6f69b1154439391184c03ccf0e52e3b289447f0c6176be07fb24bc180aa", + "body_text": "fn field_error(ui: &mut Ui, error: Option<&str>) {\n if let Some(error) = error {\n ui.label(\n RichText::new(error)\n .small()\n .color(Color32::from_rgb(214, 90, 90)),\n );\n }\n}", + "body_hash": "3042d8d7cb2273103987b4f80a95c9cce7e822eef3ca7aa1608fe4007945a0cd" + }, + "src/ui/api_keys.rs|crate::impl MainWindow::show_tg_keys_ui#free:71efd538c9db": { + "kind": "Free", + "file": "src/ui/api_keys.rs", + "item_path": "crate::impl MainWindow::show_tg_keys_ui#free:71efd538c9db", + "comment_kind": "Line", + "comment_text": "// Keep the form at a readable width on wide windows", + "comment_hash": "71efd538c9db7ef76aa62e82d52a142133fa263c05a5c255e2f646e8d93f5886", + "body_text": "let width = ui.available_width().min(520.0);\nlet side = ((ui.available_width() - width) / 2.0).max(0.0);", + "body_hash": "457ad585dcc4d2ff0a2aa26948296b238dd473fd7a73e7693fb4ea214f40ba69" + }, + "src/ui/api_keys.rs|crate::impl MainWindow::show_tg_keys_ui#free:b476be23ca32": { + "kind": "Free", + "file": "src/ui/api_keys.rs", + "item_path": "crate::impl MainWindow::show_tg_keys_ui#free:b476be23ca32", + "comment_kind": "Line", + "comment_text": "// The window starts small, so let the form scroll instead of being cut off", + "comment_hash": "b476be23ca32fac8d99d2dd1aaf5aafd31dcd122315373024b917270410edcd4", + "body_text": "ScrollArea::vertical()\n .auto_shrink([false, false])\n .show(ui, |ui| {});\n}", + "body_hash": "5a0f5b41c332fb2ebcb5072ffb3aa2077b4dfd6956ec51f644c561446ab5fff2" + }, + "src/ui/api_keys.rs|crate::impl TGKeys::hash_error": { + "kind": "Function", + "file": "src/ui/api_keys.rs", + "item_path": "crate::impl TGKeys::hash_error", + "comment_kind": "OuterDoc", + "comment_text": " Telegram API hashes are 32 hexadecimal characters\n", + "comment_hash": "158fa050f6c303728241cbf1ea6387f018c9e90666892825854933107f82e9ca", + "body_text": "fn hash_error(&self) -> Option<&'static str> {\n let hash = self.api_hash.trim();\n if hash.is_empty() {\n None\n } else if !hash.chars().all(|c| c.is_ascii_hexdigit()) {\n Some(\"The API hash only contains 0-9 and a-f\")\n } else if hash.len() != 32 {\n Some(\"The API hash is 32 characters long\")\n } else {\n None\n }\n }", + "body_hash": "6317e4980590b951b17b34d6048fdc6e74c0f4406e3053a6f27dab44b7d1eae1" + }, + "src/ui/api_keys.rs|crate::impl TGKeys::id_error": { + "kind": "Function", + "file": "src/ui/api_keys.rs", + "item_path": "crate::impl TGKeys::id_error", + "comment_kind": "OuterDoc", + "comment_text": " Telegram API IDs are plain numbers\n", + "comment_hash": "67d6a35e19051006b82e960ddfef2f346940e8642b8bd6406bfc6adeab4f784c", + "body_text": "fn id_error(&self) -> Option<&'static str> {\n let id = self.api_id.trim();\n if id.is_empty() {\n None\n } else if !id.chars().all(|c| c.is_ascii_digit()) {\n Some(\"The API ID only contains digits\")\n } else {\n None\n }\n }", + "body_hash": "33cf933984d9c6f2d01bfb082c33b4f5d84a450f49243a71e8a5ab4f4cd6d456" + }, + "src/ui/app.rs|crate::MainWindow::saved_lists_loaded": { + "kind": "Field", + "file": "src/ui/app.rs", + "item_path": "crate::MainWindow::saved_lists_loaded", + "comment_kind": "OuterDoc", + "comment_text": " Saved whitelist and blacklist are only loaded once, after the first connection\n", + "comment_hash": "068ff78c74cefce0ba26fdb63de22f3f515b5dec955125810a9e81c5b1171b28", + "body_text": "pub saved_lists_loaded: bool", + "body_hash": "8bc9da2fdf88d614ee17655c0bf9db112134211222dc5b367521a5ac73792f87" + }, + "src/ui/app.rs|crate::impl App for MainWindow::ui#free:052bd7e564d2": { + "kind": "Free", + "file": "src/ui/app.rs", + "item_path": "crate::impl App for MainWindow::ui#free:052bd7e564d2", + "comment_kind": "Line", + "comment_text": "// If asked to close the app, search for any temporary client and if any, logout then close the window", + "comment_hash": "052bd7e564d2ca52b651f2c7ed297f9041f35fd3b96d2c1f9f2c98f9151c67f2", + "body_text": "if ui.ctx().input(|i| i.viewport().close_requested()) {}\nmatch self.app_state {\n AppState::LoadingFontsAPI => {}\n AppState::InputAPIKeys => self.show_tg_keys_ui(ui),\n AppState::InitializedUI => {}\n }\n}", + "body_hash": "143dff4bfd1907f8565c065fb7609e04678c617db2c6434a8d6efc0a83da0e42" + }, + "src/ui/app.rs|crate::impl App for MainWindow::ui#free:54affb5a430c": { + "kind": "Free", + "file": "src/ui/app.rs", + "item_path": "crate::impl App for MainWindow::ui#free:54affb5a430c", + "comment_kind": "Line", + "comment_text": "// Right side items are added first so the text takes what is left", + "comment_hash": "54affb5a430cfcdad301dd46ca4e10d8190f5cbb19b4b2e60082f2e72c384744", + "body_text": "ui.with_layout(Layout::right_to_left(Align::Center), |ui| {});\n}", + "body_hash": "722fab2acf29b858f8ec541b5ebca5ff7b19f6b8de71171a0d5253d2444f6c82" + }, + "src/ui/app.rs|crate::impl App for MainWindow::ui#free:925db1f6db87": { + "kind": "Free", + "file": "src/ui/app.rs", + "item_path": "crate::impl App for MainWindow::ui#free:925db1f6db87", + "comment_kind": "Line", + "comment_text": "// The Scan tab already has its own progress bar", + "comment_hash": "925db1f6db87583df74c46a4c7935e753be31a21e6b972866b6a24e37c2b21e1", + "body_text": "let show_progress =\n self.counter.counting() && self.tab_state != TabState::Counter;\nlet show_spinner = self.is_processing && !self.counter.counting();\nui.horizontal(|ui| {});\nui.add_space(0.5);\n}", + "body_hash": "6dd01316986ed6b1cc37e3a1c8b2e440940499a2d03ff2a5cfe172f8f917bb8b" + }, + "src/ui/app.rs|crate::impl App for MainWindow::ui#free:ce473cd802fd": { + "kind": "Free", + "file": "src/ui/app.rs", + "item_path": "crate::impl App for MainWindow::ui#free:ce473cd802fd", + "comment_kind": "Line", + "comment_text": "// If API keys are found, start the main UI otherwise show the UI to input the API keys", + "comment_hash": "ce473cd802fd1763929156f236fa6f35f27e0435822fe24eb2665d1310b9274c", + "body_text": "if get_api_keys().is_some() {} else {}\n}", + "body_hash": "f3589942516855c68086184beccdf3d63fa92073945604435027b329a1efb186" + }, + "src/ui/app.rs|crate::impl App for MainWindow::ui#free:dbe146ec3d90": { + "kind": "Free", + "file": "src/ui/app.rs", + "item_path": "crate::impl App for MainWindow::ui#free:dbe146ec3d90", + "comment_kind": "Line", + "comment_text": "// At each UI loop, check on the receiver channel to check if there is anything\n// limit total number of messages to check on the receiver to prevent frame freeze", + "comment_hash": "dbe146ec3d902e49d1ca7e8128985f88a3b1f8e6feffa2145c3541c7aa0d6950", + "body_text": "for _ in 0..self.counter.get_comm_limit() {}\n}", + "body_hash": "95ae5aafeb68c6db64dc2e321a4f3c721934bf650e77b215c94bcf2eb4b44f9e" + }, + "src/ui/app.rs|crate::impl MainWindow::chart": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::chart", + "comment_kind": "OuterDoc", + "comment_text": " Return the currently selected chart data as mutable\n", + "comment_hash": "ebd3bc95419e2a57be46f3f85521ca0fccb2565ce3e1209e17d69ff8b095a2c8", + "body_text": "pub fn chart(&mut self) -> &mut ChartsData {\n if self.counter.total_chats() > 1 {\n &mut self.chart[self.chart_chat_index]\n } else {\n &mut self.chart[0]\n }\n }", + "body_hash": "a0429454eeabeb565eacc1f0415615a7450d6cb1e0c6a8f090a979786cdeda5c" + }, + "src/ui/app.rs|crate::impl MainWindow::chart_i": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::chart_i", + "comment_kind": "OuterDoc", + "comment_text": " Return the currently selected chart data as reference\n", + "comment_hash": "7568b0ad0208dbb4a4efa1f3318d2ebff2aa6d9ddbaffb91018830c1b53b7e61", + "body_text": "pub fn chart_i(&self) -> &ChartsData {\n if self.counter.total_chats() > 1 {\n &self.chart[self.chart_chat_index]\n } else {\n &self.chart[0]\n }\n }", + "body_hash": "b66d4532c4bb5db505775a0ef05e3a1a04f08f70e7df5c2e4311248b325d0f61" + }, + "src/ui/app.rs|crate::impl MainWindow::count": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::count", + "comment_kind": "OuterDoc", + "comment_text": " Return the currently selected chart data as mutable\n", + "comment_hash": "ebd3bc95419e2a57be46f3f85521ca0fccb2565ce3e1209e17d69ff8b095a2c8", + "body_text": "pub fn count(&mut self) -> &mut CounterCounts {\n if self.counter.total_chats() > 1 {\n &mut self.counter.counts[self.counter_chat_index]\n } else {\n &mut self.counter.counts[0]\n }\n }", + "body_hash": "26fbbb78df389a04bf1a3f4ef0c41604a0bdca1b6afaebb7de9c81b7c12c5c13" + }, + "src/ui/app.rs|crate::impl MainWindow::fade_status": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::fade_status", + "comment_kind": "OuterDoc", + "comment_text": " Success messages go back to idle after a few seconds. Warnings, errors and anything\n\n that is still running stay until something else replaces them\n", + "comment_hash": "18f64598268b5f173ee7b0c8b7cb53bf93087754c8c43112cae88cd92c692c45", + "body_text": "fn fade_status(&mut self, ui: &Ui) {\n let now = ui.input(|i| i.time);\n let text = self.process_state.to_string();\n\n if text != self.status_text {\n self.status_text = text;\n self.status_changed_at = now;\n }\n\n if self.is_processing || self.process_state.severity() != Severity::Success {\n return;\n }\n\n let remaining = STATUS_FADE_SECONDS - (now - self.status_changed_at);\n\n if remaining <= 0.0 {\n self.process_state = ProcessState::Idle;\n } else {\n ui.request_repaint_after(Duration::from_secs_f64(remaining));\n }\n }", + "body_hash": "b862f71a63a29078a338e261fb9bdf45fe70aee6f2eb3330c9c2c4c14a5a3d73" + }, + "src/ui/app.rs|crate::impl MainWindow::get_session_names": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::get_session_names", + "comment_kind": "OuterDoc", + "comment_text": " Get all the added session names\n", + "comment_hash": "9c8dfcf9d942ec0d7907ed8e55fa94d3fa763c6a96dcecbef2d8958ef3ca76a6", + "body_text": "pub fn get_session_names(&self) -> Vec {\n self.backend.session_names()\n }", + "body_hash": "5adc843d6b5c3f74efdf82fe9ebb54dc8403b2274af9890bb2f383a327be90f9" + }, + "src/ui/app.rs|crate::impl MainWindow::initial_chart_reset": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::initial_chart_reset", + "comment_kind": "OuterDoc", + "comment_text": " Only called once after the Start button is pressed for the first time\n", + "comment_hash": "4783af6e7b9ca456456ede420eac34a877d9d3293e75ba84a3bc61a620f6186f", + "body_text": "pub fn initial_chart_reset(&mut self) {\n if !self.initial_chart_reset {\n self.initial_chart_reset = true;\n let chart = &mut self.chart[0];\n chart.reset_chart();\n }\n }", + "body_hash": "468368a5aae363575c16d1aa6dba586154c7871777b66a7a60f206016f45242a" + }, + "src/ui/app.rs|crate::impl MainWindow::set_fonts": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::set_fonts", + "comment_kind": "OuterDoc", + "comment_text": " Set the fonts for egui to use or download them if does not exist\n", + "comment_hash": "f7130e4aa52daeaa4fb61195f8db1643879eb793b92ea3b3182dd96404c1f89f", + "body_text": "pub fn set_fonts(&self, ctx: &Context) {\n let font_data = get_font_data();\n\n if let Some((cjk, gentium)) = font_data {\n \n let font_cjk = Arc::new(FontData::from_owned(cjk));\n let font_gentium = Arc::new(FontData::from_owned(gentium));\n let mut font_definitions = FontDefinitions::default();\n\n font_definitions\n .font_data\n .insert(\"NotoSansCJK\".to_owned(), font_cjk);\n font_definitions\n .font_data\n .insert(\"GentiumBookPlus\".to_owned(), font_gentium);\n\n font_definitions\n .families\n .get_mut(&FontFamily::Proportional)\n .unwrap()\n .extend([\"NotoSansCJK\".to_owned(), \"GentiumBookPlus\".to_owned()]);\n\n ctx.set_fonts(font_definitions);\n } else {\n info!(\"Could not find font data. Starting download\");\n let ctx_clone = ctx.clone();\n\n self.backend.spawn(download_font(ctx_clone));\n }\n }", + "body_hash": "44696c74e8a3bb333d4a636fde32e6f9b09ea65f3ab53b8db083b012fa96848a" + }, + "src/ui/app.rs|crate::impl MainWindow::set_fonts#free:d3f499a77a45": { + "kind": "Free", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::set_fonts#free:d3f499a77a45", + "comment_kind": "Line", + "comment_text": "// Add the fonts on top of the default ones", + "comment_hash": "d3f499a77a457353467919b0babc2048eae1b2eec5a3a07394af00b150ea0e9a", + "body_text": "let font_cjk = Arc::new(FontData::from_owned(cjk));\nlet font_gentium = Arc::new(FontData::from_owned(gentium));\nlet mut font_definitions = FontDefinitions::default();\nfont_definitions\n .font_data\n .insert(\"NotoSansCJK\".to_owned(), font_cjk);\nfont_definitions\n .font_data\n .insert(\"GentiumBookPlus\".to_owned(), font_gentium);\nfont_definitions\n .families\n .get_mut(&FontFamily::Proportional)\n .unwrap()\n .extend([\"NotoSansCJK\".to_owned(), \"GentiumBookPlus\".to_owned()]);\nctx.set_fonts(font_definitions);\n}", + "body_hash": "121a222ddb8445fa58e33b0d4073140af9c8444babbd9b4c35b7e11a348886bc" + }, + "src/ui/app.rs|crate::impl MainWindow::t_chart": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::t_chart", + "comment_kind": "OuterDoc", + "comment_text": " Returns the target chart where new data should be added as mutable\n", + "comment_hash": "725c2ac7ba668445bcc1a95f23bfbeb49dc3c1bf2a93c443dce47f6308de8aae", + "body_text": "pub fn t_chart(&mut self) -> &mut ChartsData {\n let ongoing = self.counter.ongoing_chat();\n &mut self.chart[ongoing]\n }", + "body_hash": "6dca4b07d34b45d3167b0557fff41a430e84e287639405c3d37d58dc15986a13" + }, + "src/ui/app.rs|crate::impl MainWindow::t_count": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::t_count", + "comment_kind": "OuterDoc", + "comment_text": " Returns the target chart where new data should be added as mutable\n", + "comment_hash": "725c2ac7ba668445bcc1a95f23bfbeb49dc3c1bf2a93c443dce47f6308de8aae", + "body_text": "pub fn t_count(&mut self) -> &mut CounterCounts {\n let ongoing = self.counter.ongoing_chat();\n &mut self.counter.counts[ongoing]\n }", + "body_hash": "e6e6b1db367cfb81099edc631af5cf96f7a08e6c74e41e3b6cccf0555ea19838" + }, + "src/ui/app.rs|crate::impl MainWindow::t_table": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::t_table", + "comment_kind": "OuterDoc", + "comment_text": " Returns the target table where new data should be added as mutable\n", + "comment_hash": "1b69fd7f3c1fc93ec4a22018af98c92379eeb2130d95120ec9ac5ffb25f29499", + "body_text": "pub fn t_table(&mut self) -> &mut UserTableData {\n let ongoing = self.counter.ongoing_chat();\n &mut self.table[ongoing]\n }", + "body_hash": "4be53c4472f1a8f79def7837cb3f6b622ba638b4c88ad5e3a00367f29fc85c8f" + }, + "src/ui/app.rs|crate::impl MainWindow::table": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::table", + "comment_kind": "OuterDoc", + "comment_text": " Return the currently selected table data as mutable\n", + "comment_hash": "8125f886b335317711e5b753e79dadd33a6405e8a951c0657d6690af9ab22a54", + "body_text": "pub fn table(&mut self) -> &mut UserTableData {\n if self.counter.total_chats() > 1 {\n &mut self.table[self.table_chat_index]\n } else {\n &mut self.table[0]\n }\n }", + "body_hash": "3ba7b33410a842c1f8e489572ba9fcc20b164a847179e3e42834a4fc0b7a12d2" + }, + "src/ui/app.rs|crate::impl MainWindow::table_i": { + "kind": "Function", + "file": "src/ui/app.rs", + "item_path": "crate::impl MainWindow::table_i", + "comment_kind": "OuterDoc", + "comment_text": " Return the currently selected table data as reference\n", + "comment_hash": "0c13d7be1f01e543a32b395f4f0feb41d5183ff923216e07d65ae4a952fed076", + "body_text": "pub fn table_i(&self) -> &UserTableData {\n if self.counter.total_chats() > 1 {\n &self.table[self.table_chat_index]\n } else {\n &self.table[0]\n }\n }", + "body_hash": "3f2cdfa9bf961add1af106c8776cfa6fb97bebfad3ae966baa2c283af8a3985c" + }, + "src/ui/dates/handler.rs|crate::DatePickerHandler": { + "kind": "Struct", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::DatePickerHandler", + "comment_kind": "OuterDoc", + "comment_text": " Handler for the `DatePicker` in the UI for data changes\n", + "comment_hash": "43b836017a023f4adeb8c587c39c5efdb17d0bb70ce745f8a53eea8aa6fa8a29", + "body_text": "#[derive(Default)]\npub struct DatePickerHandler {\n pub from: Date,\n pub to: Date,\n last_from: Option,\n last_to: Option,\n start: Option,\n end: Option,\n}", + "body_hash": "13cd769c613fc13750f473fd48aabe77713fa86729ebeb1b117b832b8aa096f2" + }, + "src/ui/dates/handler.rs|crate::DatePickerHandler::end": { + "kind": "Field", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::DatePickerHandler::end", + "comment_kind": "OuterDoc", + "comment_text": " The newest date with at least 1 data point\n", + "comment_hash": "e14a681e02462e1bfc1c5733edac3a05d5bde06d020d4abb106fd5c607f6ebff", + "body_text": "end: Option", + "body_hash": "4086d5f0516600e53577320020beb4d74ce06fd50b9b2097f55750004ee3c611" + }, + "src/ui/dates/handler.rs|crate::DatePickerHandler::from": { + "kind": "Field", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::DatePickerHandler::from", + "comment_kind": "OuterDoc", + "comment_text": " The From Date currently selected in the UI\n", + "comment_hash": "7684aed1664560179526dc6f0bad2f363aaa15b79ec931a069621fd297fda5c0", + "body_text": "pub from: Date", + "body_hash": "ff670c051b2ec6527c723219349457e5a2b4608ccddfc9ad5dc5ffebe0d34eed" + }, + "src/ui/dates/handler.rs|crate::DatePickerHandler::last_from": { + "kind": "Field", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::DatePickerHandler::last_from", + "comment_kind": "OuterDoc", + "comment_text": " The last From date selected before the current From date\n", + "comment_hash": "cb281f8415bcebe32d1724a02c1bdbf9d9107bca730a8c971cace91c4d120037", + "body_text": "last_from: Option", + "body_hash": "c957fcff233c4cb5e8930521877e4c5e77c16a46ce74b477adb785815152dfe5" + }, + "src/ui/dates/handler.rs|crate::DatePickerHandler::last_to": { + "kind": "Field", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::DatePickerHandler::last_to", + "comment_kind": "OuterDoc", + "comment_text": " The last To date selected before the current To date\n", + "comment_hash": "e6999bcc0419f000d558a4ae50200e51571f6f028fd56f82bcbd710143083505", + "body_text": "last_to: Option", + "body_hash": "0376f3e8d5fe8beb0d3699d5a52e88c3a72d1de344d0d12262bfb4b0bd525f3c" + }, + "src/ui/dates/handler.rs|crate::DatePickerHandler::start": { + "kind": "Field", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::DatePickerHandler::start", + "comment_kind": "OuterDoc", + "comment_text": " The oldest date with at least 1 data point\n", + "comment_hash": "fe633670e4e42ef200ced239d32207a5c9695e1f3a5fdfc0b59218081abb4c1e", + "body_text": "start: Option", + "body_hash": "197e31e3e5b019677382d2b7d10176db1a9542faff62555c48967ba6342b5440" + }, + "src/ui/dates/handler.rs|crate::DatePickerHandler::to": { + "kind": "Field", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::DatePickerHandler::to", + "comment_kind": "OuterDoc", + "comment_text": " The To Date currently selected in the UI\n", + "comment_hash": "941a600c791e93f76bf75bae54108b0937eb51a84fc9709e55c46cc0331d561d", + "body_text": "pub to: Date", + "body_hash": "c44e9e83962f23616cd8ed5907676c0549bf4d1dcf43c320d3f6fbdf9bb7f8fc" + }, + "src/ui/dates/handler.rs|crate::impl DatePickerHandler::before_to_range": { + "kind": "Function", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::impl DatePickerHandler::before_to_range", + "comment_kind": "OuterDoc", + "comment_text": " Whether the given date is before the current To range\n", + "comment_hash": "9af255699cc3fece15bfe246b78c1657de9b28fd5e9821aabcf2ccc328948b15", + "body_text": "pub fn before_to_range(&self, date: NaiveDate) -> bool {\n let date = date.to_jiff();\n date < self.to\n }", + "body_hash": "106e433b5b8de2c0b41fb3c709a2d7935943ef6e238a0101df6d2d26bcd5f7f2" + }, + "src/ui/dates/handler.rs|crate::impl DatePickerHandler::check_date_change": { + "kind": "Function", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::impl DatePickerHandler::check_date_change", + "comment_kind": "OuterDoc", + "comment_text": " Verify whether the current From and To dates have changed\n", + "comment_hash": "34865858114f5bad0a798d7dcb70dd62407319ec3112232e5055ad5a907c262d", + "body_text": "pub fn check_date_change(&mut self) -> bool {\n if let Some(d) = self.last_from\n && d != self.from\n {\n if self.from > self.to {\n self.from = self.to;\n }\n\n self.last_from = Some(self.from);\n return true;\n }\n if let Some(d) = self.last_to\n && d != self.to\n {\n if self.to < self.from {\n self.to = self.from;\n }\n\n self.last_to = Some(self.to);\n return true;\n }\n false\n }", + "body_hash": "fa0922f67320cd92152fbc94d0cad538b0a764606884ca1571532da6d995b049" + }, + "src/ui/dates/handler.rs|crate::impl DatePickerHandler::reset_dates": { + "kind": "Function", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::impl DatePickerHandler::reset_dates", + "comment_kind": "OuterDoc", + "comment_text": " Reset dates to the oldest and the newest value\n", + "comment_hash": "9bf92a4228db007ca611a75a910196ba33b4e1bcabd8bb4a6292b0c7b27d1a4d", + "body_text": "pub fn reset_dates(&mut self) {\n self.from = self.start.unwrap();\n self.to = self.end.unwrap();\n self.last_from = Some(self.from);\n self.last_to = Some(self.to);\n }", + "body_hash": "b287f0ae55cccd0528ab3cc59a6f850f13a4519a254ad7fb8e1d97094cc77ee5" + }, + "src/ui/dates/handler.rs|crate::impl DatePickerHandler::update_dates": { + "kind": "Function", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::impl DatePickerHandler::update_dates", + "comment_kind": "OuterDoc", + "comment_text": " Compare the given date with the current Start and End date\n\n to find the oldest and the newest date\n", + "comment_hash": "fb0d3852ab762d1f02a343dd4099254bb93e01e72d3efcfc709f42e012fb9982", + "body_text": "pub fn update_dates(&mut self, date: NaiveDate) {\n let date = date.to_jiff();\n if self.start.is_none_or(|current| current > date) {\n self.from = date;\n self.start = Some(date);\n self.last_from = Some(date);\n }\n\n if self.end.is_none_or(|current_date| current_date < date) {\n self.to = date;\n self.end = Some(date);\n self.last_to = Some(date);\n }\n }", + "body_hash": "4251dc3562eccc0a838ce1f847e726800f54bd3962d39372138db0dd65030d27" + }, + "src/ui/dates/handler.rs|crate::impl DatePickerHandler::within_range": { + "kind": "Function", + "file": "src/ui/dates/handler.rs", + "item_path": "crate::impl DatePickerHandler::within_range", + "comment_kind": "OuterDoc", + "comment_text": " Whether the given date is whtin the current From and To range\n", + "comment_hash": "356d5b4211242e1ed0edae4d2f10f25e9ab9e6073b7880762d68cdc3436e35c2", + "body_text": "pub fn within_range(&self, date: NaiveDate) -> bool {\n let date = date.to_jiff();\n\n date >= self.from && date <= self.to\n }", + "body_hash": "9811adef92949fc8de5730183d5a756d7399726945bac6dcc5db69fb16e03519" + }, + "src/ui/dates/navigator.rs|crate::impl DateNavigator::handler": { + "kind": "Function", + "file": "src/ui/dates/navigator.rs", + "item_path": "crate::impl DateNavigator::handler", + "comment_kind": "OuterDoc", + "comment_text": " Handler and mutable\n", + "comment_hash": "4e70f9df7771f26b3cab4e82505d4e2f4e3336daca8d7e1eb7b3ffa05a975d41", + "body_text": "pub fn handler(&mut self) -> &mut DatePickerHandler {\n &mut self.handler\n }", + "body_hash": "0ece3451a7b20a77aadbc34ae5fcdafa247321e0e06a1d2678e27212defe08ae" + }, + "src/ui/dates/navigator.rs|crate::impl DateNavigator::handler_i": { + "kind": "Function", + "file": "src/ui/dates/navigator.rs", + "item_path": "crate::impl DateNavigator::handler_i", + "comment_kind": "OuterDoc", + "comment_text": " Handler and not mutable\n", + "comment_hash": "657046bc776969074d76e3cbec46accfac171e1aa8f5c051a596466e33980db1", + "body_text": "pub fn handler_i(&self) -> &DatePickerHandler {\n &self.handler\n }", + "body_hash": "c19cd86ea27f8a0adcfd47043f19d75e9b556d1eabd26a1f557a7eca77692449" + }, + "src/ui/events/account.rs|crate::impl MainWindow::on_sessions_dropped#free:b1ec719a95c4": { + "kind": "Free", + "file": "src/ui/events/account.rs", + "item_path": "crate::impl MainWindow::on_sessions_dropped#free:b1ec719a95c4", + "comment_kind": "Line", + "comment_text": "// The list got shorter, keep the selected session in range", + "comment_hash": "b1ec719a95c42073d9340d38fd0026a794e046ed167a2d0576000cef2be4f92f", + "body_text": "self.counter.session_index = 0;\nself.process_state = ProcessState::SessionsDropped(names.join(\", \"));\n}", + "body_hash": "473e2849a55b9929c1f47b69218abcb743e44675a716c2472bc5cc96d3f9326d" + }, + "src/ui/events/account.rs|crate::impl MainWindow::on_sessions_restored#free:e901a64e22bd": { + "kind": "Free", + "file": "src/ui/events/account.rs", + "item_path": "crate::impl MainWindow::on_sessions_restored#free:e901a64e22bd", + "comment_kind": "Line", + "comment_text": "// Reloading the lists would add every saved user a second time", + "comment_hash": "e901a64e22bd9272ce2b559ccbb29b692827eb7436053739494f123febb1c202", + "body_text": "if self.saved_lists_loaded {} else {}\n}", + "body_hash": "c3615649b577425520dd8e9652293fdbb6928f83498293a53a14b3822c4d6822" + }, + "src/ui/events/mod.rs|crate::impl MainWindow::check_receiver": { + "kind": "Function", + "file": "src/ui/events/mod.rs", + "item_path": "crate::impl MainWindow::check_receiver", + "comment_kind": "OuterDoc", + "comment_text": " Handles one pending event from the Telegram side. Returns false when there was none\n", + "comment_hash": "b58595158188526501985176e5cd4d20bd2e27e95112843ae313be642d4a5b3b", + "body_text": "pub fn check_receiver(&mut self) -> bool {\n let Some(event) = self.backend.poll() else {\n return false;\n };\n\n match event {\n Event::Account(event) => self.on_account_event(event),\n Event::Scan(event) => self.on_scan_event(event),\n Event::Users(event) => self.on_users_event(event),\n Event::Failed(error) => self.on_failure(error),\n }\n true\n }", + "body_hash": "17324e1dfe4f213f955cda17a2bfa7163c8907680733d85ead338511fd07b818" + }, + "src/ui/events/scan.rs|crate::impl MainWindow::on_chat_checked#free:996d2c726cd7": { + "kind": "Free", + "file": "src/ui/events/scan.rs", + "item_path": "crate::impl MainWindow::on_chat_checked#free:996d2c726cd7", + "comment_kind": "Line", + "comment_text": "// Because we count both the start and ending message ID", + "comment_hash": "996d2c726cd7f507504f2d1c5c4c9ab981603527a7df5a4e2da9cf74ba944489", + "body_text": "let total_to_count = start_at - end_at + 1;\nlet total_session = sessions.len();\nlet per_session_value = total_to_count / total_session as i32;\ninfo!(\"Each session to process {per_session_value}~ messages\");\nself.counter.set_session_count(total_session);\nlet mut ongoing_start_at = start_at;\nlet mut ongoing_end_at = start_at - per_session_value;\nlet mut negative_added = false;\nself.backend.reset_cancel();\nfor (index, session) in sessions.into_iter().enumerate() {}\n}", + "body_hash": "8bd068ee425e2c94d31215b815ac2b89972e15a768e140e098ade2077ad69595" + }, + "src/ui/events/scan.rs|crate::impl MainWindow::on_chat_checked#free:e2e58bd4cc16": { + "kind": "Free", + "file": "src/ui/events/scan.rs", + "item_path": "crate::impl MainWindow::on_chat_checked#free:e2e58bd4cc16", + "comment_kind": "Line", + "comment_text": "// because we count both starting and end point\n// Example starting point 100, end point 1. Total session 4, per session to process 25 messages\n// First session start at 100 end at 100 - 25 = 75\n// Next session start at (last session start - per session process) end at (last session end - per session process)\n//\n// Here start at would be 75 which will overlap a message so reduce 1\n//\n// next session start at 49 end at 25 and so on", + "comment_hash": "e2e58bd4cc1661f986407aeb468cccf7c1fa1a10ac44d9eebaac2b98b9861546", + "body_text": "if !negative_added {}\n}", + "body_hash": "4f7f2975836bf9bd00d73d292e5c3719d8a5e7e032c9a36f760ac81d775bb8af" + }, + "src/ui/events/scan.rs|crate::impl MainWindow::on_count_finished#free:4ed7bbb82d50": { + "kind": "Free", + "file": "src/ui/events/scan.rs", + "item_path": "crate::impl MainWindow::on_count_finished#free:4ed7bbb82d50", + "comment_kind": "Line", + "comment_text": "// Example case end point 100, last processed 102\n// Current num 99 so end point reached\n// 101 and 100 is missing so count them as deleted", + "comment_hash": "4ed7bbb82d502a8c8f3e854c28ec71ff75d46e70931e97dfd2a77b095d937b9b", + "body_text": "if last_number != end_at {}\ninfo!(\"Counting ended for a session\");", + "body_hash": "1ab39142b41ddacc317e0898057749d3b43ca2aab9a3e5f674aeee6cab8f223c" + }, + "src/ui/events/scan.rs|crate::impl MainWindow::on_count_finished#free:a9aaf4a2fec8": { + "kind": "Free", + "file": "src/ui/events/scan.rs", + "item_path": "crate::impl MainWindow::on_count_finished#free:a9aaf4a2fec8", + "comment_kind": "Line", + "comment_text": "// Stop process sets the progress bar to 100\n// Progress only if 1 session is remaining to be completed or it was 0 (0 in normal counting)\n// Also recreate table data after counting session ends for a chat", + "comment_hash": "a9aaf4a2fec89446342b1b31963f83c1b7e57d62cea941b8d2716656ec6a1eb2", + "body_text": "if self.counter.session_remaining() <= 1 {} else {}\n}", + "body_hash": "5ac2515c03cc014b055d07f23f79ceb8ce721f395571b13907c94cd350bcf072" + }, + "src/ui/events/scan.rs|crate::impl MainWindow::on_counted_message#free:987a4b6e7dfb": { + "kind": "Free", + "file": "src/ui/events/scan.rs", + "item_path": "crate::impl MainWindow::on_counted_message#free:987a4b6e7dfb", + "comment_kind": "Line", + "comment_text": "// In single session set the progress by explicitly by counting it on the go\n// On multi session add whatever percentage there is + new value for this session", + "comment_hash": "987a4b6e7dfbbd4b62e95e9fddfb52dc2cb622553aebfa47b7cb198999f1b3c8", + "body_text": "if multi_session {} else {}\nif !blacklisted {}\nif self.t_table().reload_count() > 100 {}\n}", + "body_hash": "115f431ac33c9dc8815d2fceaec3ba1c418c697716a68cfee78ab0f09e8b7661" + }, + "src/ui/events/scan.rs|crate::impl MainWindow::on_counted_message#free:ad6ba2edc617": { + "kind": "Free", + "file": "src/ui/events/scan.rs", + "item_path": "crate::impl MainWindow::on_counted_message#free:ad6ba2edc617", + "comment_kind": "Line", + "comment_text": "// If current num = 100 and last processed = 105\n// messages with 101, 102, 103 and 104 are missing/deleted\n// The current num is already getting processed so subtract 1", + "comment_hash": "ad6ba2edc617213c39cff8753532d47224128b5ca49304015b964ed776f9f59f", + "body_text": "let total_deleted = if last_number == -1 {} else {};\nself.t_count().add_deleted_message(total_deleted);\nlet total_processed = start_from - current_message_number;\nlet processed_percentage = if total_processed != 0 {} else {};\nself.t_count().add_one_total_message();\nif whitelisted {}", + "body_hash": "7eba28f0b5d59b73e8ba5e26ea8fcc97bb812372bc20d50d29b6def2503bb343" + }, + "src/ui/services/fonts.rs|crate::download_font": { + "kind": "Function", + "file": "src/ui/services/fonts.rs", + "item_path": "crate::download_font", + "comment_kind": "OuterDoc", + "comment_text": " Downloads the app font data from github, saves them locally and loads them\n", + "comment_hash": "fd58349af08b3d8292a575341611d7f9dfb3c36334f45840e1c916f42382847d", + "body_text": "pub async fn download_font(ctx: Context) {\n let cjk_font_url =\n \"https://github.com/TheRustyPickle/Talon/raw/main/fonts/NotoSansCJK-Regular.ttc\";\n let gentium_font_url =\n \"https://github.com/TheRustyPickle/Talon/raw/main/fonts/GentiumBookPlus-Regular.ttf\";\n\n let mut gentium_font = PathBuf::from(\".\");\n let mut cjk_font = PathBuf::from(\".\");\n\n gentium_font.push(\"fonts\");\n cjk_font.push(\"fonts\");\n\n gentium_font.push(\"GentiumBookPlus-Regular.ttf\");\n cjk_font.push(\"NotoSansCJK-Regular.ttc\");\n\n let client = reqwest::Client::new();\n\n let Ok(response) = client.get(cjk_font_url).send().await else {\n error!(\"Failed to get a response for CJK font\");\n return;\n };\n\n let cjk_data = if response.status().is_success() {\n let mut file = File::create(cjk_font).unwrap();\n let response_data = response\n .bytes()\n .await\n .expect(\"Could not convert CJK response into bytes\");\n file.write_all(&response_data).unwrap();\n info!(\"Saved CJK font data successfully\");\n response_data\n } else {\n error!(\"CJK response was not a success\");\n return;\n };\n\n let Ok(response) = client.get(gentium_font_url).send().await else {\n error!(\"Failed to get a response for Gentium font\");\n return;\n };\n\n let gentium_data = if response.status().is_success() {\n let mut file = File::create(gentium_font).unwrap();\n let response_data = response\n .bytes()\n .await\n .expect(\"Could not convert gentium response into bytes\");\n file.write_all(&response_data).unwrap();\n info!(\"Saved Gentium font data successfully\");\n response_data\n } else {\n error!(\"Gentium response was not a success\");\n return;\n };\n\n let font_cjk = Arc::new(FontData::from_owned(cjk_data.to_vec()));\n let font_gentium = Arc::new(FontData::from_owned(gentium_data.to_vec()));\n let mut font_definitions = FontDefinitions::default();\n\n font_definitions\n .font_data\n .insert(\"NotoSansCJK\".to_owned(), font_cjk);\n font_definitions\n .font_data\n .insert(\"GentiumBookPlus\".to_owned(), font_gentium);\n\n font_definitions\n .families\n .get_mut(&FontFamily::Proportional)\n .unwrap()\n .extend([\"NotoSansCJK\".to_owned(), \"GentiumBookPlus\".to_owned()]);\n\n ctx.set_fonts(font_definitions);\n}", + "body_hash": "c62c4d66106598252011cc3942f5869346c87447f35da30a255be3984c127948" + }, + "src/ui/state/states.rs|crate::PackedWhitelistedUser": { + "kind": "Struct", + "file": "src/ui/state/states.rs", + "item_path": "crate::PackedWhitelistedUser", + "comment_kind": "OuterDoc", + "comment_text": " Saved form of a `PeerRef`.\n", + "comment_hash": "747042fd8754a57df263adf55a466b287680caccc8292ab3d517aa299d5bd890", + "body_text": "#[derive(Deserialize, Serialize, PartialEq, Eq, Hash)]\npub struct PackedWhitelistedUser {\n pub peer_id: i64,\n pub access_hash: i64,\n pub seen_by: String,\n}", + "body_hash": "55411f3483365c3252e0e426cbc787dd5ae2f579e70cbe30b3b29a8430895338" + }, + "src/ui/state/states.rs|crate::ProcessState::InitialClientConnectionSuccessful": { + "kind": "Variant", + "file": "src/ui/state/states.rs", + "item_path": "crate::ProcessState::InitialClientConnectionSuccessful", + "comment_kind": "OuterDoc", + "comment_text": " Connection summary and whether at least one session failed to connect\n", + "comment_hash": "890450bb72f7ec09d80b2654f245e106d030fd237ca24826d15f373cd72c0ae3", + "body_text": "InitialClientConnectionSuccessful(String, bool)", + "body_hash": "886ec25ae08a324609009d9a5410c821f6c616dd614f69d7326c1a1b7ffb8250" + }, + "src/ui/state/states.rs|crate::ProcessState::SessionsDropped": { + "kind": "Variant", + "file": "src/ui/state/states.rs", + "item_path": "crate::ProcessState::SessionsDropped", + "comment_kind": "OuterDoc", + "comment_text": " Names of the sessions that were logged out and removed\n", + "comment_hash": "034974d93628d3e215f20e1c3dee9a253c8243165cfc9293d2f1880e94500131", + "body_text": "SessionsDropped(String)", + "body_hash": "aa8138833b0aebbc62a5070a434e5eddde40a7e41df3020506831f3421378ccf" + }, + "src/ui/state/states.rs|crate::ProcessState::SessionsRefreshed": { + "kind": "Variant", + "file": "src/ui/state/states.rs", + "item_path": "crate::ProcessState::SessionsRefreshed", + "comment_kind": "OuterDoc", + "comment_text": " Sessions that are logged in after a refresh\n", + "comment_hash": "6329bae79fe4aa9676a5b027c66ead90b4e6f6460257b730744a5cbfab1ef6b4", + "body_text": "SessionsRefreshed(usize)", + "body_hash": "6755ef1e0a6583cb49c79d52991f89647c98a4e82755811aadec56bf2d54f21a" + }, + "src/ui/state/states.rs|crate::Severity": { + "kind": "Enum", + "file": "src/ui/state/states.rs", + "item_path": "crate::Severity", + "comment_kind": "OuterDoc", + "comment_text": " How the status bar should present a `ProcessState`\n", + "comment_hash": "58be4993462db59794a8dac3ac3d8b1adb6b3b5831f6f2266958dcfc6919d08a", + "body_text": "#[derive(Clone, Copy, PartialEq, Eq)]\npub enum Severity {\n Idle,\n Busy,\n Success,\n Warning,\n Error,\n}", + "body_hash": "55981b583ba5fab4d6d68d8d12fbb2b163efeb288dc18992978f812a89e71b3e" + }, + "src/ui/state/states.rs|crate::impl PackedBlacklistedUser::new": { + "kind": "Function", + "file": "src/ui/state/states.rs", + "item_path": "crate::impl PackedBlacklistedUser::new", + "comment_kind": "OuterDoc", + "comment_text": " Returns `None` if the peer has no id that can be saved\n", + "comment_hash": "1ed1944e87e03c7b422b7e3a9e0de91163cf222da62ffbe4c59919b35e100663", + "body_text": "pub fn new(peer: PeerRef, seen_by: String) -> Option {\n Some(Self {\n peer_id: peer.id.bot_api_dialog_id()?,\n access_hash: peer.auth.hash(),\n seen_by,\n })\n }", + "body_hash": "3f07e10182f23b9cec704cb569cefae8395d2953c018df266ad1debbc656744d" + }, + "src/ui/state/states.rs|crate::impl PackedWhitelistedUser::new": { + "kind": "Function", + "file": "src/ui/state/states.rs", + "item_path": "crate::impl PackedWhitelistedUser::new", + "comment_kind": "OuterDoc", + "comment_text": " Returns `None` if the peer has no id that can be saved\n", + "comment_hash": "1ed1944e87e03c7b422b7e3a9e0de91163cf222da62ffbe4c59919b35e100663", + "body_text": "pub fn new(peer: PeerRef, seen_by: String) -> Option {\n Some(Self {\n peer_id: peer.id.bot_api_dialog_id()?,\n access_hash: peer.auth.hash(),\n seen_by,\n })\n }", + "body_hash": "3f07e10182f23b9cec704cb569cefae8395d2953c018df266ad1debbc656744d" + }, + "src/ui/state/states.rs|crate::peer_details": { + "kind": "Function", + "file": "src/ui/state/states.rs", + "item_path": "crate::peer_details", + "comment_kind": "OuterDoc", + "comment_text": " Returns the name, username and bare id of a peer\n", + "comment_hash": "475298865041b608905c35163703b5646189b77c3e114681e190a22a3e97a717", + "body_text": "pub fn peer_details(peer: &Peer) -> (String, String, i64) {\n \n let name = match peer {\n Peer::User(user) => user.full_name(),\n _ => peer.name().unwrap_or_default().to_string(),\n };\n let name = if name.is_empty() {\n \"Deleted Account\".to_string()\n } else {\n name\n };\n\n let username = peer.username().unwrap_or(\"Empty\").to_string();\n\n (name, username, peer.id().bare_id().unwrap_or(0))\n}", + "body_hash": "cb1a7ad4a9aa7e8f7eca196736fcbe66538513960ad607ae1c0b282342cf34c3" + }, + "src/ui/state/states.rs|crate::peer_details#free:5b8bcbfc6a5a": { + "kind": "Free", + "file": "src/ui/state/states.rs", + "item_path": "crate::peer_details#free:5b8bcbfc6a5a", + "comment_kind": "Line", + "comment_text": "// As per grammers lib doc, empty name can be given if it's a deleted account", + "comment_hash": "5b8bcbfc6a5a740270cb18e6e1c8a546fea3c5f8c3dd7252d9f3de15838eb24d", + "body_text": "let name = match peer {\n Peer::User(user) => user.full_name(),\n _ => peer.name().unwrap_or_default().to_string(),\n };\nlet name = if name.is_empty() {} else {};\nlet username = peer.username().unwrap_or(\"Empty\").to_string();\n(name, username, peer.id().bare_id().unwrap_or(0))\n}", + "body_hash": "01b15170b66300e021b13b86df5e82a3d384f21e4177a503ed73b7fd0dd38650" + }, + "src/ui/state/states.rs|crate::unpack_peer_ref": { + "kind": "Function", + "file": "src/ui/state/states.rs", + "item_path": "crate::unpack_peer_ref", + "comment_kind": "OuterDoc", + "comment_text": " Rebuilds a `PeerRef` from the saved integers\n", + "comment_hash": "e4b71a7f77464ad879d5faa78c3d825e8057c4c8a21c005495c500dd7da17604", + "body_text": "fn unpack_peer_ref(peer_id: i64, access_hash: i64) -> Option {\n Some(PeerRef {\n id: PeerId::from_bot_api_dialog_id(peer_id)?,\n auth: PeerAuth::from_hash(access_hash),\n })\n}", + "body_hash": "aaf4b1d05f39314b0aff93c64e688e6f6e4b32bfcafa0ac1c87a88fbb4d82e16" + }, + "src/ui/tabs/accounts.rs|crate::SessionData::code_sent": { + "kind": "Field", + "file": "src/ui/tabs/accounts.rs", + "item_path": "crate::SessionData::code_sent", + "comment_kind": "OuterDoc", + "comment_text": " A login code was sent and is waiting to be entered\n", + "comment_hash": "1e17550e75f96cef057c297ee1f29e4a7e60329772135c8e5cf29a13f4c3029d", + "body_text": "pub code_sent: bool", + "body_hash": "6a2dd66f5118fdd4001da81c989f6c0bbaad7053b6160cc82ff7f0845e2a7ec6" + }, + "src/ui/tabs/accounts.rs|crate::SessionData::password_mode": { + "kind": "Field", + "file": "src/ui/tabs/accounts.rs", + "item_path": "crate::SessionData::password_mode", + "comment_kind": "OuterDoc", + "comment_text": " Whether the account asked for a password\n", + "comment_hash": "29269eb0d2e85aad4777f846e25dbafc33f36379441fa3a806b0a40b864c1c6d", + "body_text": "pub password_mode: bool", + "body_hash": "afe9565c8c485e2804c9aca5194b79e0d68511b82aaba15edf3679fe9a0ba1d2" + }, + "src/ui/tabs/accounts.rs|crate::impl MainWindow::request_login_code": { + "kind": "Function", + "file": "src/ui/tabs/accounts.rs", + "item_path": "crate::impl MainWindow::request_login_code", + "comment_kind": "OuterDoc", + "comment_text": " Asks Telegram to send a login code to the phone number\n", + "comment_hash": "c41146e756df8cd2126f7e643580539ca85649e9bf08641779e55951d740f195", + "body_text": "fn request_login_code(&mut self) {\n self.is_processing = true;\n self.process_state = ProcessState::SendingTGCode;\n\n self.backend.send(Command::RequestLoginCode {\n session: self.session.get_session_name(),\n phone: self.session.get_phone_number(),\n temporary: self.session.get_is_temporary(),\n });\n }", + "body_hash": "cfd97afc220791d898e764a119a4b8a507eb4e2a022f43fe36b2ebd245b825c3" + }, + "src/ui/tabs/accounts.rs|crate::impl MainWindow::show_session_ui#free:98a3af4c6ec4": { + "kind": "Free", + "file": "src/ui/tabs/accounts.rs", + "item_path": "crate::impl MainWindow::show_session_ui#free:98a3af4c6ec4", + "comment_kind": "Line", + "comment_text": "// Once a code was sent or a password is required, the account details are locked in", + "comment_hash": "98a3af4c6ec4e80b20e1824ff144e362878ce16a4d80291533fffc9f77c89add", + "body_text": "let locked = self.session.code_sent || self.session.password_mode;\nCard::new().title(\"ACCOUNT\").show(ui, |ui| {});\nui.add_space(8.0);\nCard::new().title(\"VERIFICATION\").show(ui, |ui| {});\nui.add_space(12.0);\nui.horizontal(|ui| {});\n}", + "body_hash": "ebae2e09139fd643ed536a429512d3e2d183125de9b25f3a546aa3e1e222fd55" + }, + "src/ui/tabs/accounts.rs|crate::impl MainWindow::sign_in_code": { + "kind": "Function", + "file": "src/ui/tabs/accounts.rs", + "item_path": "crate::impl MainWindow::sign_in_code", + "comment_kind": "OuterDoc", + "comment_text": " Tries to log in with the given login code\n", + "comment_hash": "b272d7be7ed3f474915c88c5195e3cfb3494513c62c1ac6508b87b35a4e4110f", + "body_text": "fn sign_in_code(&mut self) {\n self.is_processing = true;\n self.process_state = ProcessState::LogInWithCode;\n\n self.backend.send(Command::SubmitLoginCode {\n code: self.session.get_tg_code(),\n });\n }", + "body_hash": "ae63f00f369cc2cb1b3e1b02e6dc0ca50867193d66174e3ca5bd757bb8deb029" + }, + "src/ui/tabs/accounts.rs|crate::impl MainWindow::sign_in_password": { + "kind": "Function", + "file": "src/ui/tabs/accounts.rs", + "item_path": "crate::impl MainWindow::sign_in_password", + "comment_kind": "OuterDoc", + "comment_text": " Tries to log in with the given login password\n", + "comment_hash": "2f6e26b3126d7a7a4044d8cdd3a65f2bb88fa39fbd9f0190c46bcd39b636be2a", + "body_text": "fn sign_in_password(&mut self) {\n self.is_processing = true;\n self.process_state = ProcessState::LogInWithPassword;\n\n self.backend.send(Command::SubmitPassword {\n password: self.session.get_password(),\n });\n }", + "body_hash": "e74d64c38f419983797214b56483e3b225f96cde7f397a2a2a473fbd007cc3b0" + }, + "src/ui/tabs/blacklist.rs|crate::impl BlacklistData::add_to_blacklist": { + "kind": "Function", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl BlacklistData::add_to_blacklist", + "comment_kind": "OuterDoc", + "comment_text": " Add a new row to the UI\n", + "comment_hash": "f9448b507cb8e8f5c241cf70ef287f87058d15db2614561549bf99312afe4f2a", + "body_text": "pub fn add_to_blacklist(\n &mut self,\n name: String,\n username: String,\n id: i64,\n belongs_to: PeerRef,\n seen_by: String,\n ) {\n let name = if name.is_empty() {\n String::from(\"Deleted Account\")\n } else {\n name\n };\n\n info!(\"Adding {name} to blacklist, seen by {seen_by}\");\n self.all_ids.insert(id);\n self.table.add_modify_row(|_rows| {\n let to_add = BlackListRowData::new(name, username, id, belongs_to, seen_by);\n Some(to_add)\n });\n }", + "body_hash": "7178fb90b99318912c5d8ec4343dbeb77a6ed406ffe73a91070661fa7e56f611" + }, + "src/ui/tabs/blacklist.rs|crate::impl BlacklistData::is_user_blacklisted": { + "kind": "Function", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl BlacklistData::is_user_blacklisted", + "comment_kind": "OuterDoc", + "comment_text": " Check if user is blacklisted/in the blacklist UI\n", + "comment_hash": "e4e421b32e78211f8d6e735b1bde26f273052ecf432cf198fe7c6cb0bc8857d4", + "body_text": "pub fn is_user_blacklisted(&self, id: i64) -> bool {\n self.all_ids.contains(&id)\n }", + "body_hash": "bac80b583293521e93c76c036938d874b0e5c5d9f77dc8734f68991cc9c24d0b" + }, + "src/ui/tabs/blacklist.rs|crate::impl BlacklistData::remove_all": { + "kind": "Function", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl BlacklistData::remove_all", + "comment_kind": "OuterDoc", + "comment_text": " Removes all row from blacklist and saves the result\n", + "comment_hash": "1e8fa639d3791799fc7a66df21ea27dbdbcf01fe410ecb4f6378f2b0cf8504a3", + "body_text": "fn remove_all(&mut self) -> Vec {\n info!(\"Removing all users from blacklist\");\n let row_keys = self.all_ids.iter().copied().collect();\n self.table.clear_all_rows();\n self.save_blacklisted_users(true);\n self.all_ids.clear();\n\n row_keys\n }", + "body_hash": "6277a6192ba2ad11dae8aeae26d90398976c6cb81a9e1f7df2078138a47266af" + }, + "src/ui/tabs/blacklist.rs|crate::impl BlacklistData::remove_selected": { + "kind": "Function", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl BlacklistData::remove_selected", + "comment_kind": "OuterDoc", + "comment_text": " Removes selected row from blacklist and saves the result\n", + "comment_hash": "9176e2c47f94fc3e0de98c5c143736edd73bd1f80bd03a23237be8e99b385d1b", + "body_text": "fn remove_selected(&mut self) -> Vec {\n let active_rows = self.table.get_selected_rows();\n\n let mut row_ids = Vec::new();\n for i in &active_rows {\n info!(\n \"Removing user {} | {} from blacklist\",\n i.row_data.username, i.row_data.id\n );\n self.all_ids.remove(&i.row_data.id);\n self.table.add_modify_row(|rows| {\n rows.remove(&i.id);\n row_ids.push(i.row_data.id);\n None\n });\n }\n self.save_blacklisted_users(true);\n row_ids\n }", + "body_hash": "ec16001a5e482c2d0615abaa3ffd0e5e09ef80d9ef6e4148edd3565eb3fc99be" + }, + "src/ui/tabs/blacklist.rs|crate::impl BlacklistData::save_blacklisted_users": { + "kind": "Function", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl BlacklistData::save_blacklisted_users", + "comment_kind": "OuterDoc", + "comment_text": " Save the current row data in the blacklist json\n", + "comment_hash": "2ce11385fd0971824f12c98ea889705434f64b8de00ce4faed8e9db1cebad9a2", + "body_text": "pub fn save_blacklisted_users(&self, overwrite: bool) {\n let packed_chats = self\n .table\n .get_all_rows()\n .values()\n .filter_map(|row| {\n PackedBlacklistedUser::new(row.row_data.belongs_to, row.row_data.seen_by.clone())\n })\n .collect();\n\n save_blacklisted_users(packed_chats, overwrite);\n }", + "body_hash": "2a084f87f1830c81002cd20c1b9d43038aa966122894fb1536d722f4047b7280" + }, + "src/ui/tabs/blacklist.rs|crate::impl MainWindow::load_blacklisted_users#free:20ee6dc293f1": { + "kind": "Free", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl MainWindow::load_blacklisted_users#free:20ee6dc293f1", + "comment_kind": "Line", + "comment_text": "// This case means it failed to deserialize the json or is using the old blacklist json format\n// All previous data will be removed", + "comment_hash": "20ee6dc293f1b04d8350a95005ec80213f9fdc9aeea7f9a03809f8ff9e2e747e", + "body_text": "error!(\"Failed to deserialize the blacklist users json file. Deleting saved json data\");\nsave_blacklisted_users(Vec::new(), true);\nself.process_state = ProcessState::FailedLoadBlacklistedUsers;\nself.is_processing = false;\nreturn;\n}", + "body_hash": "0b0675216aa794b2262fbb4868bde88d151d0de62e3a89cf53b986b30f375956" + }, + "src/ui/tabs/blacklist.rs|crate::impl MainWindow::load_blacklisted_users#free:6090cac164c7": { + "kind": "Free", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl MainWindow::load_blacklisted_users#free:6090cac164c7", + "comment_kind": "Line", + "comment_text": "// This function will never be called if there are no sessions detected.\n// Unnecessary to handle in case is empty", + "comment_hash": "6090cac164c79336005cfbf87e09532f439fcff3a6235af56550a24fe609a963", + "body_text": "let all_blacklisted_users = get_blacklisted();\nif all_blacklisted_users.is_err() {}", + "body_hash": "2c7cebdf26d0821270670ca4932bbeaf6df1413b0cc58158e41eff5482161453" + }, + "src/ui/tabs/blacklist.rs|crate::impl MainWindow::load_blacklisted_users#free:7219a1656e43": { + "kind": "Free", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl MainWindow::load_blacklisted_users#free:7219a1656e43", + "comment_kind": "Line", + "comment_text": "// separate blacklist data by seen_by as the key and the peer refs as the value", + "comment_hash": "7219a1656e433de634d6fa758b1525ad7abd043985255be992606bb24e17dada", + "body_text": "let separated_data = separate_blacklist_by_seen(all_blacklisted_users.unwrap());\nif separated_data.is_empty() {}", + "body_hash": "a4cb926a611bcbe90e36ca649608c7a4f59408854f805a287c7889ae5b4663da" + }, + "src/ui/tabs/blacklist.rs|crate::impl MainWindow::load_blacklisted_users#free:c9ef7382c447": { + "kind": "Free", + "file": "src/ui/tabs/blacklist.rs", + "item_path": "crate::impl MainWindow::load_blacklisted_users#free:c9ef7382c447", + "comment_kind": "Line", + "comment_text": "// Open a thread for each unique session found in the blacklist json and pass the relevant peer refs to that thread\n// `peer_refs` cannot be empty as the key will only exist if there is at least one peer ref found", + "comment_hash": "c9ef7382c44746eb72300375fa484568c1e87e46cc79085080aab5f8a1afce48", + "body_text": "for (seen_by, peer_refs) in separated_data {}\n}", + "body_hash": "39cf96ac55a94c98cc5f3c01b20a28ea04b2bac692a5840c9f09c25468c9a1ff" + }, + "src/ui/tabs/charts.rs|crate::ChartsData::daily_bars": { + "kind": "Field", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::ChartsData::daily_bars", + "comment_kind": "OuterDoc", + "comment_text": " Pre-saved Bars to for the daily chart, used for both Message and User\n", + "comment_hash": "fa88ddbe62994c7c795c89881f84dc9aafdd57e684c900c40ee619e7eedb9f58", + "body_text": "daily_bars: Option>>", + "body_hash": "141929e633d5bb6d532ae7cc05a3d19a8a424923c6b2b38a71c0f32eed154188" + }, + "src/ui/tabs/charts.rs|crate::ChartsData::daily_labels": { + "kind": "Field", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::ChartsData::daily_labels", + "comment_kind": "OuterDoc", + "comment_text": " Hover labels for the daily chart, key = x value in chart. Values = (date, total message, whitelist message)\n", + "comment_hash": "20ad6b58d1fc309a41c8a5b1cb6f4f35da95c2bae0e29b81351975cb76da9f34", + "body_text": "daily_labels: HashMap", + "body_hash": "309ff44e512d558915c42db7eac50badddb19df73b329da2eefc500f1f2a02ae" + }, + "src/ui/tabs/charts.rs|crate::ChartsData::hourly_bars": { + "kind": "Field", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::ChartsData::hourly_bars", + "comment_kind": "OuterDoc", + "comment_text": " Pre-saved Bars to for the hourly chart, used for both Message and User\n", + "comment_hash": "52e69b2bd71b0ce79837e41e8ab37c56ab374c7aa6cc023188e9f07b10a1f6a0", + "body_text": "hourly_bars: Option>>", + "body_hash": "ed4915f386bae9690844f4987227817231f3005e10c957466db94c2043efa749" + }, + "src/ui/tabs/charts.rs|crate::ChartsData::hourly_labels": { + "kind": "Field", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::ChartsData::hourly_labels", + "comment_kind": "OuterDoc", + "comment_text": " Hover labels for the hourly chart, key = x value in chart. Values = (date, total message, whitelist message)\n", + "comment_hash": "650ed557693400c4814125892059d93ef8625879ffec5719d9bbed14cb8a9e71", + "body_text": "hourly_labels: HashMap", + "body_hash": "a3185d39cde47914f6ab3ecea85c8af492fa694e90b32e86f77f732369954d0e" + }, + "src/ui/tabs/charts.rs|crate::ChartsData::labels": { + "kind": "Field", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::ChartsData::labels", + "comment_kind": "OuterDoc", + "comment_text": " Hover labels, key = x value in chart. Values = (date, total message, whitelist message)\n", + "comment_hash": "619dd83e697fa7e1b032eb2e1aabd89a6b4856f7b2261d383974ec6d6354be46", + "body_text": "labels: HashMap", + "body_hash": "a05da9ce18fa4bd2e7e7494edb5dd60e0f3e503b076e3a7f0d9cdb0b7d864adf" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::add_message": { + "kind": "Function", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::add_message", + "comment_kind": "OuterDoc", + "comment_text": " Takes a message creation time and the unique user to create necessary data to form a chart\n", + "comment_hash": "ef6be24ccc63613a2ca705ead33be5ed8481fcca525d1f71871d967babf7e37b", + "body_text": "pub fn add_message(\n &mut self,\n time: NaiveDateTime,\n date: NaiveDate,\n add_to: String,\n client_name: &str,\n ) {\n \n \n let hourly_time = time.with_second(0).unwrap().with_minute(0).unwrap();\n let daily_time = time\n .with_second(0)\n .unwrap()\n .with_minute(0)\n .unwrap()\n .with_hour(0)\n .unwrap();\n let monthly_time = time\n .with_second(0)\n .unwrap()\n .with_minute(0)\n .unwrap()\n .with_hour(0)\n .unwrap()\n .with_day(1)\n .unwrap();\n\n let sent_on = time.weekday();\n\n \n let week_day_name = Weekday::Mon;\n let week_num = time.iso_week().week();\n let time_year = time.iso_week().year();\n\n let weekly_time = NaiveDate::from_isoywd_opt(time_year, week_num, week_day_name)\n .unwrap()\n .and_hms_opt(0, 0, 0)\n .unwrap();\n\n \n \n if let Some(Some(last_hour)) = self.last_hour.get_mut(client_name) {\n let missing_hour = (*last_hour - hourly_time).num_hours();\n\n let mut ongoing_hour = *last_hour;\n for _ in 0..missing_hour {\n let to_add = ongoing_hour.checked_sub_signed(Duration::hours(1)).unwrap();\n self.hourly_message.entry(to_add).or_default();\n ongoing_hour = to_add;\n }\n *last_hour = hourly_time;\n } else {\n self.last_hour\n .insert(client_name.to_string(), Some(hourly_time));\n }\n\n if let Some(Some(last_day)) = self.last_day.get_mut(client_name) {\n let missing_day = (*last_day - daily_time).num_days();\n\n let mut ongoing_day = *last_day;\n for _ in 0..missing_day {\n let to_add = ongoing_day.checked_sub_signed(Duration::days(1)).unwrap();\n self.daily_message.entry(to_add).or_default();\n ongoing_day = to_add;\n }\n *last_day = daily_time;\n } else {\n self.last_day\n .insert(client_name.to_string(), Some(daily_time));\n }\n\n if let Some(Some(last_week)) = self.last_week.get_mut(client_name) {\n let missing_week = (*last_week - weekly_time).num_weeks();\n\n let mut ongoing_week = *last_week;\n for _ in 0..missing_week {\n let to_add = ongoing_week.checked_sub_signed(Duration::weeks(1)).unwrap();\n self.weekly_message.entry(to_add).or_default();\n ongoing_week = to_add;\n }\n *last_week = weekly_time;\n } else {\n self.last_week\n .insert(client_name.to_string(), Some(weekly_time));\n }\n\n if let Some(Some(last_month)) = self.last_month.get_mut(client_name) {\n let mut ongoing_month = *last_month;\n\n \n while ongoing_month > monthly_time {\n let to_add = ongoing_month\n .checked_sub_signed(Duration::days(2))\n .unwrap()\n .with_day(1)\n .unwrap();\n self.monthly_message.entry(to_add).or_default();\n ongoing_month = to_add;\n }\n *last_month = monthly_time;\n } else {\n self.last_month\n .insert(client_name.to_string(), Some(monthly_time));\n }\n\n let counter = self.hourly_message.entry(hourly_time).or_default();\n let target_user = counter.entry(add_to.clone()).or_insert(0);\n *target_user += 1;\n\n let counter = self.daily_message.entry(daily_time).or_default();\n let target_user = counter.entry(add_to.clone()).or_insert(0);\n *target_user += 1;\n\n let counter = self.weekly_message.entry(weekly_time).or_default();\n let target_user = counter.entry(add_to.clone()).or_insert(0);\n *target_user += 1;\n\n let counter = self.monthly_message.entry(monthly_time).or_default();\n let target_user = counter.entry(add_to.clone()).or_insert(0);\n *target_user += 1;\n\n let counter = self.weekday_message.get_mut(&(sent_on as u8)).unwrap();\n let target_user = counter.entry(add_to).or_insert(0);\n *target_user += 1;\n\n self.reset_saved_bars();\n self.date_nav.handler().update_dates(date);\n }", + "body_hash": "ac3950ec969b36430f0b74e362f820eb878fd78205cc6ae172d097915a6336f1" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::add_message#free:968ca8beb9c3": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::add_message#free:968ca8beb9c3", + "comment_kind": "Line", + "comment_text": "// If last day is January 10, current day is January 5, add January 6 to 9 with 0 value\n// Apply the same for all of them", + "comment_hash": "968ca8beb9c3cd3137872d1f936823480b8ddedb007ef8fabdbecb1679e9d2b7", + "body_text": "if let Some(Some(last_hour)) = self.last_hour.get_mut(client_name) {} else {}\nif let Some(Some(last_day)) = self.last_day.get_mut(client_name) {} else {}\nif let Some(Some(last_week)) = self.last_week.get_mut(client_name) {} else {}\nif let Some(Some(last_month)) = self.last_month.get_mut(client_name) {} else {}\nlet counter = self.hourly_message.entry(hourly_time).or_default();\nlet target_user = counter.entry(add_to.clone()).or_insert(0);\n*target_user += 1;\nlet counter = self.daily_message.entry(daily_time).or_default();\nlet target_user = counter.entry(add_to.clone()).or_insert(0);\n*target_user += 1;\nlet counter = self.weekly_message.entry(weekly_time).or_default();\nlet target_user = counter.entry(add_to.clone()).or_insert(0);\n*target_user += 1;\nlet counter = self.monthly_message.entry(monthly_time).or_default();\nlet target_user = counter.entry(add_to.clone()).or_insert(0);\n*target_user += 1;\nlet counter = self.weekday_message.get_mut(&(sent_on as u8)).unwrap();\nlet target_user = counter.entry(add_to).or_insert(0);\n*target_user += 1;\nself.reset_saved_bars();\nself.date_nav.handler().update_dates(date);\n}", + "body_hash": "291810ce78f53bf8fca5f40ef3aa7e0cc671159b12c43e26a71baffa7a1faa45" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::add_message#free:dbc14fac89f3": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::add_message#free:dbc14fac89f3", + "comment_kind": "Line", + "comment_text": "// All monthly date has the day set as 1. Reducing 2 days would take us to the previous month", + "comment_hash": "dbc14fac89f300a39af18f773f5a9f3dd4c66826a4186e58251dce7b459133d6", + "body_text": "while ongoing_month > monthly_time {}\n*last_month = monthly_time;\n}", + "body_hash": "40112be7a344c1d4e25ba88879753be3a44cc9c507e674f11cca78359c906de9" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::add_message#free:e980e70c85e4": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::add_message#free:e980e70c85e4", + "comment_kind": "Line", + "comment_text": "// Keep a common value among messages for example messages sent within the same hour,\n// reset the second and minute value to 0 so these messages can be grouped", + "comment_hash": "e980e70c85e4095c388494c64f0f87c057480130afa317715a96b36c81082fe4", + "body_text": "let hourly_time = time.with_second(0).unwrap().with_minute(0).unwrap();\nlet daily_time = time\n .with_second(0)\n .unwrap()\n .with_minute(0)\n .unwrap()\n .with_hour(0)\n .unwrap();\nlet monthly_time = time\n .with_second(0)\n .unwrap()\n .with_minute(0)\n .unwrap()\n .with_hour(0)\n .unwrap()\n .with_day(1)\n .unwrap();\nlet sent_on = time.weekday();", + "body_hash": "c9371f41cd15e131d45cbf5fe464a7d731a8f09e0413d1cb1e43944e5d1117ff" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::add_message#free:ec66af01945c": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::add_message#free:ec66af01945c", + "comment_kind": "Line", + "comment_text": "// We only care about the week number for this. Set it as Monday to keep a common ground", + "comment_hash": "ec66af01945c081da2dda2484c9406daadd51b512e74b745676b0707bde864f9", + "body_text": "let week_day_name = Weekday::Mon;\nlet week_num = time.iso_week().week();\nlet time_year = time.iso_week().year();\nlet weekly_time = NaiveDate::from_isoywd_opt(time_year, week_num, week_day_name)\n .unwrap()\n .and_hms_opt(0, 0, 0)\n .unwrap();", + "body_hash": "8bbd5ea4aaef8aaad44d9c4fb7049dc84e23bf5f93b44fd82e4042694ab3f69b" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::add_to_chart": { + "kind": "Function", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::add_to_chart", + "comment_kind": "OuterDoc", + "comment_text": " Adds the user specified in the text edit in the chart\n", + "comment_hash": "f3ddc73d57c0bdb38e5de3c795264f61d03e7d8dcc1eb9c08b32e42850008a98", + "body_text": "fn add_to_chart(&mut self, to_add: String) {\n self.added_to_chart.insert(to_add);\n self.reset_saved_bars();\n }", + "body_hash": "9826ce02e3c134efab120af36fb6cfa6f68be32bf010dc7a66c9e4cfa0d28cc9" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::add_user": { + "kind": "Function", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::add_user", + "comment_kind": "OuterDoc", + "comment_text": " Adds a user available for adding in the chart\n", + "comment_hash": "0b78a5d5778ff8d066bdb49bae58fbde318e434d5a5d8ba8e78100a0049ad18a", + "body_text": "pub fn add_user(&mut self, user: String, user_id: i64) {\n self.available_users.insert(user.clone(), false);\n self.user_ids.insert(user, user_id);\n }", + "body_hash": "2de2aa23c18a5f78e2fcf09618c358d66bea363d7648903e8ad8a3edaa506ae4" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::message_whitelist_added": { + "kind": "Function", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::message_whitelist_added", + "comment_kind": "OuterDoc", + "comment_text": " Whether total message and whitelist message are added to the chart\n", + "comment_hash": "3ec4316e7570df90fc5f0c831b7a82776b4b132ec652223bc2d13e38219b4239", + "body_text": "fn message_whitelist_added(&self, row_len: usize) -> (bool, bool) {\n \n \n let whitelist = self.added_to_chart.contains(\"Show whitelisted data\") && row_len > 0;\n\n (self.added_to_chart.contains(\"Show total data\"), whitelist)\n }", + "body_hash": "32c912a8cf70e4557ec9eb18efeab36449e85697c8571ac743f73a8236417e31" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::message_whitelist_added#free:58bd0ed214f0": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::message_whitelist_added#free:58bd0ed214f0", + "comment_kind": "Line", + "comment_text": "// If there are no whitelisted users, this will be considered as not-shown. Adds extra bars\n// to the ui => consume more power.", + "comment_hash": "58bd0ed214f0ceecf005ae7b4e27b54ddc4c827f4665907c8b771765df2f43b3", + "body_text": "let whitelist = self.added_to_chart.contains(\"Show whitelisted data\") && row_len > 0;\n(self.added_to_chart.contains(\"Show total data\"), whitelist)\n}", + "body_hash": "1def1bdf5b6e3d02e077fad9721b30221ce19cfc586308a0d46620f6b4075262" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::remove_from_chart": { + "kind": "Function", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::remove_from_chart", + "comment_kind": "OuterDoc", + "comment_text": " Removes the user that was clicked on from the chart\n", + "comment_hash": "1774fbdbb1ef3ef3f2e58d44b11d8b95ddba5938bb5a1b26114afd5882d37cd1", + "body_text": "fn remove_from_chart(&mut self, user: &str) {\n self.added_to_chart.remove(user);\n self.reset_saved_bars();\n }", + "body_hash": "e17f7ca80baad5def08960fbe42baf896418b342aee4a688e7441b76b49bb54a" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::reset_chart": { + "kind": "Function", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::reset_chart", + "comment_kind": "OuterDoc", + "comment_text": " Reset chart data\n", + "comment_hash": "8e24c6fd6ecebae7b78707d5cbfcd4a61d3df9060ae4d68f57d792b873c0e91c", + "body_text": "pub fn reset_chart(&mut self) {\n self.available_users.clear();\n self.added_to_chart.clear();\n self.last_day = HashMap::new();\n self.last_hour = HashMap::new();\n self.last_month = HashMap::new();\n self.last_week = HashMap::new();\n self.daily_message.clear();\n self.hourly_message.clear();\n self.weekly_message.clear();\n self.daily_message.clear();\n self.user_ids.clear();\n self.weekday_message.clear();\n self.reset_saved_bars();\n\n let mut ongoing_value = Some(Weekday::Mon);\n\n while let Some(value) = ongoing_value {\n self.weekday_message.insert(value as u8, HashMap::new());\n let next_day = value.succ();\n\n if next_day == Weekday::Mon {\n ongoing_value = None;\n } else {\n ongoing_value = Some(next_day);\n }\n }\n\n \n self.added_to_chart.insert(\"Show total data\".to_string());\n self.added_to_chart\n .insert(\"Show whitelisted data\".to_string());\n self.available_users\n .insert(\"Show total data\".to_string(), true);\n self.available_users\n .insert(\"Show whitelisted data\".to_string(), true);\n\n self.date_nav = DateNavigator::default();\n }", + "body_hash": "308cee38e2cc3b72076ab5c3c2a042cbe05e0002d6a93b4736e13ae2234f7fac" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::reset_chart#free:5e21d09c9502": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::reset_chart#free:5e21d09c9502", + "comment_kind": "Line", + "comment_text": "// These two are added to the chart by default", + "comment_hash": "5e21d09c950269546b44e6072224b655fd4f3771f3c88fc252a7638cfcac19eb", + "body_text": "self.added_to_chart.insert(\"Show total data\".to_string());\nself.added_to_chart\n .insert(\"Show whitelisted data\".to_string());\nself.available_users\n .insert(\"Show total data\".to_string(), true);\nself.available_users\n .insert(\"Show whitelisted data\".to_string(), true);\nself.date_nav = DateNavigator::default();\n}", + "body_hash": "04cfeecff4ff0255754dac743f5fb9335409086ab32baf7d4d8ecd756bc54572" + }, + "src/ui/tabs/charts.rs|crate::impl ChartsData::reset_saved_bars": { + "kind": "Function", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl ChartsData::reset_saved_bars", + "comment_kind": "OuterDoc", + "comment_text": " Clears all pre-saved bars\n", + "comment_hash": "0249e3b93d00f14c2866987a02f4abd64a06d9f0f26a6d3553dd0b3813a27692", + "body_text": "pub fn reset_saved_bars(&mut self) {\n self.hourly_bars = None;\n self.daily_bars = None;\n self.hourly_labels.clear();\n self.daily_labels.clear();\n }", + "body_hash": "821db15aa12cffce99d68a18ad1b05ea11e7d42345439719da0abca4c57b3b5b" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_active_user_chart#free:01049097eaa1": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_active_user_chart#free:01049097eaa1", + "comment_kind": "Line", + "comment_text": "// Check whether the date is within the given range and whether before the to value\n// BTreeMap is already sorted. We are going from low to high so if already beyond the\n// to value, there is no use iterating further and break", + "comment_hash": "01049097eaa15a3359a4e2eba11af5d9c6ae507bfb948ac121743f79c3055e99", + "body_text": "let within_range = self.chart_i().date_nav.handler_i().within_range(key_date);\nlet before_to_range = self\n .chart_i()\n .date_nav\n .handler_i()\n .before_to_range(key_date);\nif !within_range && before_to_range {}\nif !within_range {}\nlet mut total_user = 0;\nlet mut whitelisted_user = 0;\nif show_whitelisted_message {} else if show_total_message {}\nif show_total_message {}\nif show_whitelisted_message {}\npoint_dates.insert(\n index as i64,\n (*key, total_user as u64, whitelisted_user as u64),\n );\n}", + "body_hash": "bdf8f4de922992070263e7a33285c80fa5a3ac88d6eb52f9561025ebddcaf6a1" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_active_user_chart#free:5c2cc175bb10": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_active_user_chart#free:5c2cc175bb10", + "comment_kind": "Line", + "comment_text": "// Key = The common time where one or more message may have been sent\n// user = All users that sent messages to this common time + the amount of message", + "comment_hash": "5c2cc175bb1045adcfb39aeb31d7a3e015fbba25913b0de368ea361a6ffe8651", + "body_text": "for (index, (key, user)) in to_iter {}\nif self.chart().chart_timing == ChartTiming::Hourly {}\nif self.chart().chart_timing == ChartTiming::Daily {}\nself.chart().labels = point_dates;\nself.display_chart(ui, show_total_message, show_whitelisted_message, bar_list);\n}", + "body_hash": "febe4928515fc5bdb6b6648c76d8639f1f67c68785ca870e11abecf4cc6a666f" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_chart#free:462b26446a88": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_chart#free:462b26446a88", + "comment_kind": "Line", + "comment_text": "// User data stacking only happens on Message chart", + "comment_hash": "462b26446a888239f7b8a3fb40f1421c9856c986e48296a6e549c113cf043750", + "body_text": "if self.chart().chart_type == ChartType::Message {}\nlet timing = self.chart().chart_timing;\nlet chart_type = self.chart().chart_type;\nlet is_weekday =\n chart_type == ChartType::MessageWeekDay || chart_type == ChartType::ActiveUserWeekDay;\nlet labels = if timing == ChartTiming::Hourly && !is_weekday {} else if timing == ChartTiming::Daily && !is_weekday {} else {};\nlet label_fmt = move |position: &HoverPosition| {};\nPlot::new(\"Plot\")\n .legend(Legend::default().background_alpha(0.0))\n .auto_bounds([true; 2])\n .clamp_grid(true)\n .label_formatter(label_fmt)\n .show(ui, |plot_ui| {});\n}", + "body_hash": "d9e1ce4288e190f2b5e675094911ccbf05e5f13ce12b82096b90099c4e8b7542" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_chart#free:85ad7229b7bf": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_chart#free:85ad7229b7bf", + "comment_kind": "Line", + "comment_text": "// Whitelist message should be above the total message\n// In case the date picker is used the bar list may not contain the following bar names\n// even if they are already in the list", + "comment_hash": "85ad7229b7bf03fa15b3fcd9c88d4fb964bb5b07fba6a60e75ebcbe1be2a52ae", + "body_text": "if show_whitelisted_message {} else if show_total_message\n && let Some(total_message_bars) = bar_list.remove(\"Show total data\")\n {}", + "body_hash": "0da7cec88373160f67fcdaf46e9c6d92b4fa5101ff24110d398f2af4d4bc4a66" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_chart#free:b1327f11a77d": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_chart#free:b1327f11a77d", + "comment_kind": "Line", + "comment_text": "// Only triggered when Something other than total and whitelisted message is added to\n// the chart.\n// All charts must be stacked by all the previous charts\n// Chart 3 will be stacked by chart 1 and 2\n// The target is the bottom chart is total message => whitelist => the rest of the users", + "comment_hash": "b1327f11a77da757bcfdb14ec2128b9a05d754701d7b371b1c368ef380e0f3d1", + "body_text": "if !bar_list.is_empty() {}\n}", + "body_hash": "617e08c5e5a6a3291f340b668e1b609cae096020d273bd40cf97b2b8cfe713ab" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_message_chart#free:01049097eaa1": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_message_chart#free:01049097eaa1", + "comment_kind": "Line", + "comment_text": "// Check whether the date is within the given range and whether before the to value\n// BTreeMap is already sorted. We are going from low to high so if already beyond the\n// to value, there is no use iterating further and break", + "comment_hash": "01049097eaa15a3359a4e2eba11af5d9c6ae507bfb948ac121743f79c3055e99", + "body_text": "let within_range = self.chart_i().date_nav.handler_i().within_range(key_date);\nlet before_to_range = self\n .chart_i()\n .date_nav\n .handler_i()\n .before_to_range(key_date);\nif !within_range && before_to_range {}\nif !within_range {}\nlet arg = index as f64;\nlet mut total_message = 0;\nlet mut whitelisted_message = 0;", + "body_hash": "f2149fd7effb8a1d049011eb509321650c60c4e5ffb853c1e1032c934d26568b" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_message_chart#free:29e90300c4a3": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_message_chart#free:29e90300c4a3", + "comment_kind": "Line", + "comment_text": "// All of the bar charts must have the same amount of Bar.\n// In case a common time does not include a user that is added in the chart\n// add a 0 value bar", + "comment_hash": "29e90300c4a3b322b0ce6a5bd079a501b01c1ca473d4ba32bbe0eee48e652f98", + "body_text": "for i in &self.chart_i().added_to_chart {}", + "body_hash": "61ccd3c4280cabdd0cb3e4490bafe96419a818b15cb84d852df8f13dc59653c9" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_message_chart#free:5c2cc175bb10": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_message_chart#free:5c2cc175bb10", + "comment_kind": "Line", + "comment_text": "// Key = The common time where one or more message may have been sent\n// user = All users that sent messages to this common time + the amount of message", + "comment_hash": "5c2cc175bb1045adcfb39aeb31d7a3e015fbba25913b0de368ea361a6ffe8651", + "body_text": "for (index, (key, user)) in to_iter {}\nif self.chart().chart_timing == ChartTiming::Hourly {}\nif self.chart().chart_timing == ChartTiming::Daily {}\nself.chart().labels = point_dates;\nself.display_chart(ui, show_total_message, show_whitelisted_message, bar_list);\n}", + "body_hash": "febe4928515fc5bdb6b6648c76d8639f1f67c68785ca870e11abecf4cc6a666f" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_message_chart#free:dc26ef21cdfa": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_message_chart#free:dc26ef21cdfa", + "comment_kind": "Line", + "comment_text": "// Go through all the users that sent message in this common time and create a bar if necessary", + "comment_hash": "dc26ef21cdfa7f5149e26ef2537c514de147156e2ef0b496db8ed9b5d9a43919", + "body_text": "for (user_name, num) in user {}\nif show_total_message {}\nif show_whitelisted_message {}\npoint_dates.insert(index as i64, (*key, total_message, whitelisted_message));\n}", + "body_hash": "5af6565d03e8d55a00f6a60efeabba926cc641710e11151a360e2d00df9bda28" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_message_chart#free:f454e7f56969": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_message_chart#free:f454e7f56969", + "comment_kind": "Line", + "comment_text": "// If user in the chart, add the message count otherwise ignore", + "comment_hash": "f454e7f569699c37d8d9b67b1cf13c156aa61f21e6744b715a49445aba4654f9", + "body_text": "let user_in_chart = self.chart_i().added_to_chart.contains(user_name);\nif user_in_chart {}\n}", + "body_hash": "b8989543f272c76a1b1f6e7869a5e849af15c12e1cb17cde04475ef4c3d650a9" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_weekday_active_user_chart#free:247d04972567": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_weekday_active_user_chart#free:247d04972567", + "comment_kind": "Line", + "comment_text": "// Key = weekday num\n// user = All users that sent messages to this common time + the amount of message", + "comment_hash": "247d049725676f2848b95d2046ba716632a23bf42fd145ab54f96d4be27e21c4", + "body_text": "for (index, (key, user)) in to_iter {}\nself.chart().labels = point_dates;\nself.display_chart(ui, show_total_message, show_whitelisted_message, bar_list);\n}", + "body_hash": "592d5f257ef4d50a742ee52ee0d7358c21a0c0ecb9e6782a12b71f184e71e6ec" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::display_weekday_message_chart#free:488f39b7a640": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::display_weekday_message_chart#free:488f39b7a640", + "comment_kind": "Line", + "comment_text": "// Key = Weekday num\n// user = All users that sent messages to this common time + the amount of message", + "comment_hash": "488f39b7a6409542b6fc80924e364a9448e231353ab6664b6a197f54dc6871da", + "body_text": "for (index, (key, user)) in to_iter {}\nself.chart().labels = point_dates;\nself.display_chart(ui, show_total_message, show_whitelisted_message, bar_list);\n}", + "body_hash": "592d5f257ef4d50a742ee52ee0d7358c21a0c0ecb9e6782a12b71f184e71e6ec" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::show_charts_ui#free:5d86efc9a6ee": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::show_charts_ui#free:5d86efc9a6ee", + "comment_kind": "Line", + "comment_text": "// We do not care about changes in other timing as only these two are saved\n// If the last time Message type was selected, and currently it's user, reset saved bar\n// data and vice versa.", + "comment_hash": "5d86efc9a6ee7ddede988c506f5fe3af0c4d6b432ad964762a5f95f0fd189da1", + "body_text": "if is_message_user && current_type != last_type {}\nmatch self.chart().chart_type {\n ChartType::Message => self.display_message_chart(ui),\n ChartType::ActiveUser => self.display_active_user_chart(ui),\n ChartType::MessageWeekDay => self.display_weekday_message_chart(ui),\n ChartType::ActiveUserWeekDay => self.display_weekday_active_user_chart(ui),\n }\n}", + "body_hash": "0dd1574c66a8602bfc21a9ec6d63d64b5bb0d6e994e943c1ef65b5f2ac354f15" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::show_charts_ui#free:79466e440dd0": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::show_charts_ui#free:79466e440dd0", + "comment_kind": "Line", + "comment_text": "// Set pre-saved hourly and daily bars to None if date selection changes so they can be\n// rendered again and saved with the latest data", + "comment_hash": "79466e440dd0154c0d01884851ecd6e9d85a4a92138f22958b91618164f3a05b", + "body_text": "if date_enabled && self.chart().date_nav.handler().check_date_change() {}\nui.separator();\n}", + "body_hash": "6a033a58cbe5577cb4f0041ac22cf2182f751d1d0783835c55870d1a695e6061" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::show_charts_ui#free:7c85025c6588": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::show_charts_ui#free:7c85025c6588", + "comment_kind": "Line", + "comment_text": "// Don't show any date stuff if it's a weekday chart", + "comment_hash": "7c85025c6588f13bc4971ff506f79ca6be9b7e60bdfbcb8ad733b24e633cf27e", + "body_text": "if not_weekday_chart {}\nui.horizontal(|ui| {});\nlet current_type = &self.chart_i().chart_type;\nlet last_type = &self.chart_i().last_chart_type;\nlet is_message_user =\n current_type == &ChartType::Message || current_type == &ChartType::ActiveUser;", + "body_hash": "e3176afe862c644474b046f6e76de652de033de05f4487a7d55ad1aa537dcd6a" + }, + "src/ui/tabs/charts.rs|crate::impl MainWindow::show_charts_ui#free:e2d454ba3511": { + "kind": "Free", + "file": "src/ui/tabs/charts.rs", + "item_path": "crate::impl MainWindow::show_charts_ui#free:e2d454ba3511", + "comment_kind": "Line", + "comment_text": "// Monitor for H and L key presses", + "comment_hash": "e2d454ba35119506622137c4cc106c1daea43daea48b8a430ca3d42e262a40cb", + "body_text": "if date_enabled {}", + "body_hash": "5774282b20d79e269d1952ceb26c20c6c129a9e41f799efeb18fae74ce1fd6c7" + }, + "src/ui/tabs/scan.rs|crate::impl MainWindow::get_selected_session": { + "kind": "Function", + "file": "src/ui/tabs/scan.rs", + "item_path": "crate::impl MainWindow::get_selected_session", + "comment_kind": "OuterDoc", + "comment_text": " Returns the session name that is selected on the combo box\n", + "comment_hash": "d64a6e02be3cc17b90fef2841b42edaef789ae591f5bddf0e5602401b6866479", + "body_text": "pub fn get_selected_session(&self) -> String {\n let all_sessions = self.get_session_names();\n let selected_index = self.counter.session_index;\n\n if let Some(session) = all_sessions.get(selected_index) {\n session.to_owned()\n } else {\n String::new()\n }\n }", + "body_hash": "79685461d929b00d021c612f3cf857d928319d0b891b2a92bae1950e50777132" + }, + "src/ui/tabs/scan.rs|crate::impl MainWindow::reload_sessions": { + "kind": "Function", + "file": "src/ui/tabs/scan.rs", + "item_path": "crate::impl MainWindow::reload_sessions", + "comment_kind": "OuterDoc", + "comment_text": " Checks the connected sessions and connects saved ones that are missing\n", + "comment_hash": "0bbdc075775d6e32a3b79aa65df2479b57683060fba0efbb1d563a35a9384e70", + "body_text": "fn reload_sessions(&mut self) {\n let connected = self.get_session_names();\n let new_files: Vec = find_session_files()\n .into_iter()\n .filter(|file| !connected.contains(&file.replace(\".sqlite\", \"\")))\n .collect();\n\n self.is_processing = true;\n self.process_state = ProcessState::ConnectingSessions;\n self.backend.send(Command::RefreshSessions { new_files });\n }", + "body_hash": "c0064432efad55600594b7c7111e57bafbaf9f736ff93594f7c23208326d1c22" + }, + "src/ui/tabs/scan.rs|crate::impl MainWindow::show_counter_ui#free:70165d46a6ce": { + "kind": "Free", + "file": "src/ui/tabs/scan.rs", + "item_path": "crate::impl MainWindow::show_counter_ui#free:70165d46a6ce", + "comment_kind": "Line", + "comment_text": "// Laid out from the bottom: progress bar last, the main button right above it", + "comment_hash": "70165d46a6cea4d435cc2990298d729fee813407ed29fb16fc9ed97609f483a1", + "body_text": "ui.with_layout(Layout::bottom_up(Align::Min), |ui| {});\nself.counter.detected_chat =\n chat_to_text(&self.counter.get_start_from(), &self.counter.get_end_at());\n}", + "body_hash": "928371370ae7ecccdc5434469dce5fc06ea276d93e89fd2344b4e60dc07616c7" + }, + "src/ui/tabs/users.rs|crate::UserTableData::user_data": { + "kind": "Field", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::UserTableData::user_data", + "comment_kind": "OuterDoc", + "comment_text": " Key: The Date where at least one message/User was found\n\n Value: A hashmap of the founded User with their user id as the key\n\n Contains all data points and UI points are recreated from here\n", + "comment_hash": "3fa85b6bf2a0549158bf92cc6c0924e8ba3fe2f1391ee25947a268d9ab73ad52", + "body_text": "user_data: HashMap>", + "body_hash": "d5d399f181fefcb13ce82ca948d0f09cc2ea66e6840ef26dd7c0fdb87f6ba0e3" + }, + "src/ui/tabs/users.rs|crate::impl MainWindow::blacklist_selected_rows": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl MainWindow::blacklist_selected_rows", + "comment_kind": "OuterDoc", + "comment_text": " Marks all the rows with at least 1 column selected as blacklisted\n", + "comment_hash": "4f3ee6bb57a722764b052966939536ac3145f7f4481621425898636d1a9f475b", + "body_text": "fn blacklist_selected_rows(&mut self) {\n let table_selected_rows = self.table().table.get_selected_rows();\n let mut selected_rows = Vec::new();\n\n for selected in &table_selected_rows {\n let row_data = &selected.row_data;\n if row_data.name != \"Anonymous/Unknown\" && row_data.belongs_to.is_some() {\n selected_rows.push(row_data);\n }\n }\n\n let total_to_blacklist = selected_rows.len();\n let mut all_ids = Vec::new();\n let mut names = Vec::new();\n for row in selected_rows {\n let chart_name = to_chart_name(row.username.clone(), &row.name, row.id);\n names.push(chart_name);\n\n all_ids.push(row.id);\n\n self.blacklist.add_to_blacklist(\n row.name.clone(),\n row.username.clone(),\n row.id,\n row.belongs_to.unwrap(),\n row.seen_by.clone(),\n );\n }\n\n for chart in self.chart_all() {\n chart.clear_blacklisted(&names);\n }\n\n for table in self.table_all() {\n table.remove_blacklisted_rows(&all_ids);\n }\n\n self.blacklist.save_blacklisted_users(false);\n self.process_state = ProcessState::UsersBlacklisted(total_to_blacklist);\n }", + "body_hash": "dcd5d9f6c0398315b7338651f60fcc313007a1459808dda2762a3ad433979ad5" + }, + "src/ui/tabs/users.rs|crate::impl MainWindow::show_user_table_ui#free:8b55d8388864": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl MainWindow::show_user_table_ui#free:8b55d8388864", + "comment_kind": "Line", + "comment_text": "// recreate the rows if either of dates have changed", + "comment_hash": "8b55d83888648c57ad1f0e1630a8875d9fa31e6b15e986eae0a67eaae36bf153", + "body_text": "if date_enabled && self.table().date_nav.handler().check_date_change() {}\nui.add_space(5.0);\nlet mut clip_added = 0;\nlet to_whitelist_selected = self.table().table.config.whitelist_rows;\nlet to_blacklist_selected = self.table().table.config.blacklisted_rows;\nlet to_copy = self.table().table.config.copy_selected;\nlet to_select_all = self.table().table.config.select_all_rows;\nif to_whitelist_selected {}\nif to_blacklist_selected {}\nif to_copy {}\nif to_select_all {}\nself.table().table.show_ui(ui, |builder| {});\n}", + "body_hash": "48cc17d1c53d42e9a7e6cc14b5e9cdb7600eb1b9d828b78b683837b9cdca181b" + }, + "src/ui/tabs/users.rs|crate::impl MainWindow::show_user_table_ui#free:d3ab8cf51391": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl MainWindow::show_user_table_ui#free:d3ab8cf51391", + "comment_kind": "Line", + "comment_text": "// Date section remains disabled while data processing is ongoing or the table is empty", + "comment_hash": "d3ab8cf5139185a19caa833b50bc0c7a06e80de292d185adc0bba2b0232cbd62", + "body_text": "Card::new().show(ui, |ui| {});\nui.add_space(6.0);\nui.add_enabled_ui(date_enabled, |ui| {});\nui.add_space(6.0);", + "body_hash": "3678992a02340020b58aa8e1f18387f323e9555134457ce5a6be6646afd086cd" + }, + "src/ui/tabs/users.rs|crate::impl MainWindow::show_user_table_ui#free:e2d454ba3511": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl MainWindow::show_user_table_ui#free:e2d454ba3511", + "comment_kind": "Line", + "comment_text": "// Monitor for H and L key presses", + "comment_hash": "e2d454ba35119506622137c4cc106c1daea43daea48b8a430ca3d42e262a40cb", + "body_text": "if date_enabled {}", + "body_hash": "5774282b20d79e269d1952ceb26c20c6c129a9e41f799efeb18fae74ce1fd6c7" + }, + "src/ui/tabs/users.rs|crate::impl MainWindow::whitelist_selected_rows": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl MainWindow::whitelist_selected_rows", + "comment_kind": "OuterDoc", + "comment_text": " Marks all the rows with at least 1 column selected as whitelisted\n", + "comment_hash": "9a54fb04a04584f014ce82847ea37d88af5e78acd299529bc15a34d87d2401c6", + "body_text": "fn whitelist_selected_rows(&mut self) {\n let table_selected_rows = self.table().table.get_selected_rows();\n let mut selected_rows = Vec::new();\n\n for selected in &table_selected_rows {\n let row_data = &selected.row_data;\n if row_data.name != \"Anonymous/Unknown\" && row_data.belongs_to.is_some() {\n selected_rows.push(row_data);\n }\n }\n\n let total_to_whitelist = selected_rows.len();\n let mut all_ids = Vec::new();\n\n for row in selected_rows {\n all_ids.push(row.id);\n self.whitelist.add_to_whitelist(\n row.name.clone(),\n row.username.clone(),\n row.id,\n row.belongs_to.unwrap(),\n row.seen_by.clone(),\n );\n }\n\n self.table().set_as_whitelisted(&all_ids);\n self.chart().reset_saved_bars();\n\n self.whitelist.save_whitelisted_users(false);\n self.process_state = ProcessState::UsersWhitelisted(total_to_whitelist);\n }", + "body_hash": "df78e627a627878f1961a215c4db0c3f04460d1722df2dbc0d5428ece8484e6c" + }, + "src/ui/tabs/users.rs|crate::impl UserRowData::increase_message_by": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserRowData::increase_message_by", + "comment_kind": "OuterDoc", + "comment_text": " Increment total message count by `amount`\n", + "comment_hash": "acdd00499f6174bbc5d2d1f97b1e19f0bba1db7113a7602d54172fc8667cda47", + "body_text": "fn increase_message_by(&mut self, amount: u32) {\n self.total_message += amount;\n }", + "body_hash": "e73bf4da88ddf3949967aa3fb7642e72916edef0101b6792104b015b58459371" + }, + "src/ui/tabs/users.rs|crate::impl UserRowData::increment_total_char": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserRowData::increment_total_char", + "comment_kind": "OuterDoc", + "comment_text": " Increment total char count by `char_num`\n", + "comment_hash": "08fd86ba05a081df47009f166ca8f26b648385bd0661b1e2bfd82064f604c6b8", + "body_text": "fn increment_total_char(&mut self, char_num: u32) {\n self.total_char += char_num;\n self.average_char = self.total_char / self.total_message;\n }", + "body_hash": "ac7f6b5593bc2452582a71e3c9feb5cfd7d47e8c208d9220934753f09c5ff763" + }, + "src/ui/tabs/users.rs|crate::impl UserRowData::increment_total_message": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserRowData::increment_total_message", + "comment_kind": "OuterDoc", + "comment_text": " Increment total message count by 1\n", + "comment_hash": "d234febd9ee13abf116a24ff070047cfa0c2a3110eec50ea7ada6f90146376c0", + "body_text": "fn increment_total_message(&mut self) {\n self.total_message += 1;\n }", + "body_hash": "c4cf157fd6f4563d447d81c2e8e5ad09bdbdc51b2d858b628301e59c29cfb098" + }, + "src/ui/tabs/users.rs|crate::impl UserRowData::increment_total_word": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserRowData::increment_total_word", + "comment_kind": "OuterDoc", + "comment_text": " Increment total word count by `word_num`\n", + "comment_hash": "4b8bf0911cebd6cd5c45fe095e7c6b760e76a4809de95278829ecfc2f595b921", + "body_text": "fn increment_total_word(&mut self, word_num: u32) {\n self.total_word += word_num;\n self.average_word = self.total_word / self.total_message;\n }", + "body_hash": "80e19d5c1d28b4a6698026bf5bdba949bd5e1f986a2c76b36d9ccea92d4722b2" + }, + "src/ui/tabs/users.rs|crate::impl UserRowData::set_first_seen": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserRowData::set_first_seen", + "comment_kind": "OuterDoc", + "comment_text": " Update the date this user was first seen in the chat\n", + "comment_hash": "d7fe1bd5a677262af0f4c944bd8e8311a55aa24f314390028346187d3cbed286", + "body_text": "fn set_first_seen(&mut self, date: NaiveDateTime) {\n self.first_seen = date;\n }", + "body_hash": "9360e2fb6b8a8a227f6f409ae7bf611c0461bb944324548b53c406b76e9bfcad" + }, + "src/ui/tabs/users.rs|crate::impl UserRowData::set_last_seen": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserRowData::set_last_seen", + "comment_kind": "OuterDoc", + "comment_text": " Update the date this user was last seen in the chat\n", + "comment_hash": "7823865d8aa6b4e01dd9f467b0527e4720eb74c8b9a4d28a214269c20d7f9001", + "body_text": "fn set_last_seen(&mut self, date: NaiveDateTime) {\n self.last_seen = date;\n }", + "body_hash": "b5ff100298c894baa616f436ef2bcc7aca578ef402b67a0753a7f7caefaf3b2a" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::add_user": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::add_user", + "comment_kind": "OuterDoc", + "comment_text": " Add a user to the table\n", + "comment_hash": "0ec11de6230f7265236851bb366d62663920fc482bbc1eb95333b99e9434003f", + "body_text": "pub fn add_user(\n &mut self,\n sender: Option<&Peer>,\n sender_ref: Option,\n date: NaiveDate,\n datetime: NaiveDateTime,\n seen_by: String,\n blacklisted: bool,\n ) -> (i64, String, String) {\n let user_id;\n let full_name;\n let username;\n\n if let Some(peer) = sender {\n (full_name, username, user_id) = peer_details(peer);\n } else {\n \n user_id = 0;\n full_name = \"Anonymous/Unknown\".to_string();\n username = \"Empty\".to_string();\n }\n\n if !blacklisted {\n let user_row = UserRowData::new(\n &full_name, &username, user_id, false, sender_ref, datetime, seen_by,\n );\n\n entry_insert_user(&mut self.user_data, user_row, user_id, date);\n }\n\n (user_id, full_name, username)\n }", + "body_hash": "f8ec711a4b46023cf21c143fad1259de03aaf20111de0ee3f73c9edc4e591911" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::add_user#free:e77d437a292c": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::add_user#free:e77d437a292c", + "comment_kind": "Line", + "comment_text": "// If there is no Peer value then it could be an anonymous user", + "comment_hash": "e77d437a292c8880a9109fab6b3969ed23a65ed17696bb14abdfb0e163b62e92", + "body_text": "user_id = 0;\nfull_name = \"Anonymous/Unknown\".to_string();\nusername = \"Empty\".to_string();\n}", + "body_hash": "e545ca6ccffa882fe4c2f30f7324959e02519105e3113ec7d60799a1e128d1d4" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::blacklisted_message_in_range": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::blacklisted_message_in_range", + "comment_kind": "OuterDoc", + "comment_text": " Total ignored blacklisted messages within the selected date range\n", + "comment_hash": "a9343a361e5b1cd1e849468a6f623c555e8c58636b45109aeb2e1a8116e2f7bd", + "body_text": "pub fn blacklisted_message_in_range(&self) -> u32 {\n self.blacklisted_messages\n .iter()\n .filter(|(date, _)| self.date_nav.handler_i().within_range(**date))\n .map(|(_, count)| count)\n .sum()\n }", + "body_hash": "bd5e55559557c1fbfcb601e4c1ff1ac4b65e93bb506c02e369e61b2fa8f9f6a1" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::count_blacklisted_message": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::count_blacklisted_message", + "comment_kind": "OuterDoc", + "comment_text": " Keep track of a message that was ignored because the sender is blacklisted\n", + "comment_hash": "bb0dd2c695ab73103eb48f76286f40128e932393c64c9670225830e03a3c3f05", + "body_text": "pub fn count_blacklisted_message(&mut self, date: NaiveDate) {\n *self.blacklisted_messages.entry(date).or_default() += 1;\n }", + "body_hash": "916b5535fa57901f926e9efd6b3ace1a32a3afa64efeed141187433f5406b5c3" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::count_user_message": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::count_user_message", + "comment_kind": "OuterDoc", + "comment_text": " Update message related column values of a row\n", + "comment_hash": "f2128b45c0876d9fdbb08e394244aa9cee0eb316e00c9f4753dcc05e149636c8", + "body_text": "pub fn count_user_message(\n &mut self,\n user_id: i64,\n message: &Message,\n date: NaiveDate,\n datetime: NaiveDateTime,\n ) {\n self.reload_count += 1;\n \n let target_data = self.user_data.get_mut(&date).unwrap();\n let user_row_data = target_data.get_mut(&user_id).unwrap();\n\n let message_text = message.text();\n\n \n if user_row_data.first_seen > datetime {\n user_row_data.set_first_seen(datetime);\n }\n\n if user_row_data.last_seen < datetime {\n user_row_data.set_last_seen(datetime);\n }\n\n self.date_nav.handler().update_dates(date);\n\n let total_char = message_text.len() as u32;\n let total_word = message_text.split_whitespace().count() as u32;\n\n user_row_data.increment_total_message();\n user_row_data.increment_total_word(total_word);\n user_row_data.increment_total_char(total_char);\n }", + "body_hash": "ff01c03bb72c624e1c7c1441b0b4bff4c045bd1506f8e13e572c8d73acd658f6" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::count_user_message#free:859310ae319a": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::count_user_message#free:859310ae319a", + "comment_kind": "Line", + "comment_text": "// If a user sends multiple messages in a day, that specific day data needs to be updated", + "comment_hash": "859310ae319a00b92c6271e07b9b440fd8dfc8bd3d0b1a5e112683b2d35fcd53", + "body_text": "let target_data = self.user_data.get_mut(&date).unwrap();\nlet user_row_data = target_data.get_mut(&user_id).unwrap();\nlet message_text = message.text();", + "body_hash": "baff82358310ef54a5eb2cbae7e8791e1b16214b0573145ea682eb2fce9d7b39" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::count_user_message#free:915e534c94c2": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::count_user_message#free:915e534c94c2", + "comment_kind": "Line", + "comment_text": "// Update last and first seen in this date for this user", + "comment_hash": "915e534c94c2913fcd7d74805214f99dcdaff9d47e07dc9e7e3a7cac4392e210", + "body_text": "if user_row_data.first_seen > datetime {}\nif user_row_data.last_seen < datetime {}\nself.date_nav.handler().update_dates(date);\nlet total_char = message_text.len() as u32;\nlet total_word = message_text.split_whitespace().count() as u32;\nuser_row_data.increment_total_message();\nuser_row_data.increment_total_word(total_word);\nuser_row_data.increment_total_char(total_char);\n}", + "body_hash": "5ca690130fb56b9e5a7e3d9212103f08fb826b516bc3ba377183fc9e1909dfec" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::create_rows": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::create_rows", + "comment_kind": "OuterDoc", + "comment_text": " Recreate the rows that will be shown in the UI. Used only when date picker date is updated\n", + "comment_hash": "db6744d2ad4952f106c143489af623928bd29cd6355a7bb6112dc7f8b141face", + "body_text": "pub fn create_rows(&mut self) {\n let mut id_map = HashMap::new();\n self.table.clear_all_rows();\n let mut total_message = 0;\n let mut whitelisted_user = HashSet::new();\n let mut whitelisted_message = 0;\n\n \n for (date, data) in &self.user_data {\n if !self.date_nav.handler().within_range(*date) {\n continue;\n }\n\n for (id, row) in data {\n total_message += row.total_message;\n if row.whitelisted {\n whitelisted_user.insert(row.id);\n whitelisted_message += row.total_message;\n }\n\n if let Some(row_id) = id_map.get(id) {\n self.table.add_modify_row(|rows| {\n let target_row = rows.get_mut(row_id).unwrap();\n let user_row_data = &mut target_row.row_data;\n if user_row_data.first_seen > row.first_seen {\n user_row_data.set_first_seen(row.first_seen);\n }\n\n if user_row_data.last_seen < row.last_seen {\n user_row_data.set_last_seen(row.last_seen);\n }\n\n let total_char = row.total_char;\n let total_word = row.total_word;\n let total_message = row.total_message;\n\n user_row_data.increase_message_by(total_message);\n user_row_data.increment_total_word(total_word);\n user_row_data.increment_total_char(total_char);\n None\n });\n } else {\n let new_id = self.table.add_modify_row(|_| Some(row.clone()));\n id_map.insert(row.id, new_id.unwrap());\n }\n }\n }\n self.total_whitelisted_message = whitelisted_message;\n self.total_message = total_message;\n self.total_whitelisted_user = whitelisted_user.len() as u32;\n self.table.recreate_rows();\n }", + "body_hash": "b5d8fb1f4c5f51c6f4d9f1791ecbfb8d958106e9ba82bf718cf6865faaac2d26" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::create_rows#free:6cdd7ee232a3": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::create_rows#free:6cdd7ee232a3", + "comment_kind": "Line", + "comment_text": "// Go by all the data that are within the range and join them together", + "comment_hash": "6cdd7ee232a35e3de1ce06031a761ef7d3ffa0c81fcead6a1600b2fca9b85159", + "body_text": "for (date, data) in &self.user_data {}\nself.total_whitelisted_message = whitelisted_message;\nself.total_message = total_message;\nself.total_whitelisted_user = whitelisted_user.len() as u32;\nself.table.recreate_rows();\n}", + "body_hash": "68d2aeb0cf2453aef5e06427ee3ba10c9d9e7a8ba3fe7c74d1219b52c062404b" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::remove_blacklisted_rows#free:1e51b150fcdc": { + "kind": "Free", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::remove_blacklisted_rows#free:1e51b150fcdc", + "comment_kind": "Line", + "comment_text": "// Messages that were already counted for this user now count as blacklisted", + "comment_hash": "1e51b150fcdc7ba03bf2fe6346f1cfea925ae70808159a12099fc034f8d44230", + "body_text": "if let Some(row) = row_data.remove(id) {}\n}", + "body_hash": "35a0d4ee817b9d7f685923b03a9d8520022dcc4dceedd1bd42dcfdd140681195" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::remove_whitelist": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::remove_whitelist", + "comment_kind": "OuterDoc", + "comment_text": " Remove whitelist status from a row if exists\n", + "comment_hash": "33f6adece7c618299c2d219c041e5eed5279b39549e9b5bc9da76804e98648a4", + "body_text": "pub fn remove_whitelist(&mut self, user_id: &[i64]) {\n for row_data in self.user_data.values_mut() {\n for (id, row) in row_data.iter_mut() {\n for u_id in user_id {\n if id == u_id {\n row.whitelisted = false;\n }\n }\n }\n }\n self.create_rows();\n }", + "body_hash": "eda0a0d84ddfe052ae7f8bdc4f0366784eef5e81339e410b0e8cf951d044e263" + }, + "src/ui/tabs/users.rs|crate::impl UserTableData::set_as_whitelisted": { + "kind": "Function", + "file": "src/ui/tabs/users.rs", + "item_path": "crate::impl UserTableData::set_as_whitelisted", + "comment_kind": "OuterDoc", + "comment_text": " Mark a row as whitelisted if exists\n", + "comment_hash": "64840676041c402995551ca01fbf19592b3611fc60a30e81cc67d0695766ade5", + "body_text": "pub fn set_as_whitelisted(&mut self, user_id: &[i64]) {\n for row_data in self.user_data.values_mut() {\n for (id, row) in row_data.iter_mut() {\n for u_id in user_id {\n if id == u_id {\n row.whitelisted = true;\n }\n }\n }\n }\n self.create_rows();\n }", + "body_hash": "560f52d05ca0fc4e03c69d876a16086da9088e1edd397fde5f04a1b6a34e826e" + }, + "src/ui/tabs/whitelist.rs|crate::impl MainWindow::load_whitelisted_users#free:271207159474": { + "kind": "Free", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl MainWindow::load_whitelisted_users#free:271207159474", + "comment_kind": "Line", + "comment_text": "// This case means it failed to deserialize the json or is using the old whitelist json format\n// All previous data will be removed", + "comment_hash": "2712071594749e126ed789cf61ac399f6e9060dfd722dd97e6da82edab1b8273", + "body_text": "error!(\"Failed to deserialize a whitelist users json file. Deleting saved json data\");\nself.whitelist.save_whitelisted_users(true);\nself.process_state = ProcessState::FailedLoadWhitelistedUsers;\nself.is_processing = false;\nreturn;\n}", + "body_hash": "450de6db735cdc5665b9b21319114810ca392f2b9a50eaeae4e25236d97152f8" + }, + "src/ui/tabs/whitelist.rs|crate::impl MainWindow::load_whitelisted_users#free:6090cac164c7": { + "kind": "Free", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl MainWindow::load_whitelisted_users#free:6090cac164c7", + "comment_kind": "Line", + "comment_text": "// This function will never be called if there are no sessions detected.\n// Unnecessary to handle in case is empty", + "comment_hash": "6090cac164c79336005cfbf87e09532f439fcff3a6235af56550a24fe609a963", + "body_text": "let all_whitelisted_users = get_whitelisted();\nif all_whitelisted_users.is_err() {}", + "body_hash": "5de4f8f7703ed8d124858eed2b6b02fff85f2543e7ee5eac840317f6de42dc98" + }, + "src/ui/tabs/whitelist.rs|crate::impl MainWindow::load_whitelisted_users#free:77f837f982e6": { + "kind": "Free", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl MainWindow::load_whitelisted_users#free:77f837f982e6", + "comment_kind": "Line", + "comment_text": "// separate whitelist data by seen_by as the key and the peer refs as the value", + "comment_hash": "77f837f982e68187a787c01211a58f56b938adef82b87e4ba6f5e63dcb85ecbb", + "body_text": "let separated_data = separate_whitelist_by_seen(all_whitelisted_users.unwrap());\nif separated_data.is_empty() {}", + "body_hash": "fffe49c1af8a807135e54de0f60f61437ace8607d376426287bc397ddb8db00a" + }, + "src/ui/tabs/whitelist.rs|crate::impl MainWindow::load_whitelisted_users#free:d82af27dd032": { + "kind": "Free", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl MainWindow::load_whitelisted_users#free:d82af27dd032", + "comment_kind": "Line", + "comment_text": "// Open a thread for each unique session found in the whitelist json and pass the relevant peer refs to that thread\n// `peer_refs` cannot be empty as the key will only exist if there is at least one peer ref found", + "comment_hash": "d82af27dd0321a908da899cee16ab86a20b5eb3e2ecfbe27eff4918ab8c62d48", + "body_text": "for (seen_by, peer_refs) in separated_data {}\n}", + "body_hash": "39cf96ac55a94c98cc5f3c01b20a28ea04b2bac692a5840c9f09c25468c9a1ff" + }, + "src/ui/tabs/whitelist.rs|crate::impl WhitelistData::add_to_whitelist": { + "kind": "Function", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl WhitelistData::add_to_whitelist", + "comment_kind": "OuterDoc", + "comment_text": " Add a new row to the UI\n", + "comment_hash": "f9448b507cb8e8f5c241cf70ef287f87058d15db2614561549bf99312afe4f2a", + "body_text": "pub fn add_to_whitelist(\n &mut self,\n name: String,\n username: String,\n id: i64,\n belongs_to: PeerRef,\n seen_by: String,\n ) {\n let name = if name.is_empty() {\n String::from(\"Deleted Account\")\n } else {\n name\n };\n\n info!(\"Adding {name} to whitelist, seen by {seen_by}\");\n self.all_ids.insert(id);\n self.table.add_modify_row(|_rows| {\n let to_add = WhiteListRowData::new(name, username, id, belongs_to, seen_by);\n Some(to_add)\n });\n }", + "body_hash": "008d614622c79aeb85fe7de0c4a0bc42b2208e289f8451dd215a62ab32861fe8" + }, + "src/ui/tabs/whitelist.rs|crate::impl WhitelistData::is_user_whitelisted": { + "kind": "Function", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl WhitelistData::is_user_whitelisted", + "comment_kind": "OuterDoc", + "comment_text": " Check if user is whitelisted/in the whitelist UI\n", + "comment_hash": "fe8f25f3a038552bbe91d9cb7197a10c9bbdb99677ef5f4a541d0f42f144670a", + "body_text": "pub fn is_user_whitelisted(&self, id: i64) -> bool {\n self.all_ids.contains(&id)\n }", + "body_hash": "a93634e55e5727287ff9ceb3f4e09a01d68ae4ba8d940106322e3addb5b44845" + }, + "src/ui/tabs/whitelist.rs|crate::impl WhitelistData::remove_all": { + "kind": "Function", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl WhitelistData::remove_all", + "comment_kind": "OuterDoc", + "comment_text": " Removes all row from whitelist and saves the result\n", + "comment_hash": "ed4f35e28962f181acf00727e7efa3f233b42dcdbcb2bacd734ffaf2e07fe853", + "body_text": "fn remove_all(&mut self) -> Vec {\n info!(\"Removing all users from whitelist\");\n let row_keys = self.all_ids.iter().copied().collect();\n self.table.clear_all_rows();\n self.save_whitelisted_users(true);\n self.all_ids.clear();\n\n row_keys\n }", + "body_hash": "346db6eb8baea5ca111e4743f315ffaba9faf70b76f215ec6a1ce130a764eb34" + }, + "src/ui/tabs/whitelist.rs|crate::impl WhitelistData::remove_selected": { + "kind": "Function", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl WhitelistData::remove_selected", + "comment_kind": "OuterDoc", + "comment_text": " Removes selected row from whitelist and saves the result\n", + "comment_hash": "65b03ef71f947f210956020f63ad6d4503f7ed1388eb32b6d9983b83db5dad52", + "body_text": "fn remove_selected(&mut self) -> Vec {\n let active_rows = self.table.get_selected_rows();\n\n let mut row_ids = Vec::new();\n for i in &active_rows {\n info!(\n \"Removing user {} | {} from whitelist\",\n i.row_data.username, i.row_data.id\n );\n self.all_ids.remove(&i.row_data.id);\n self.table.add_modify_row(|rows| {\n rows.remove(&i.id);\n row_ids.push(i.row_data.id);\n None\n });\n }\n self.save_whitelisted_users(true);\n row_ids\n }", + "body_hash": "3b9c6df898f286c9b7e1a59627db42a3c9ca61eba9365ba606411f1d97442521" + }, + "src/ui/tabs/whitelist.rs|crate::impl WhitelistData::save_whitelisted_users": { + "kind": "Function", + "file": "src/ui/tabs/whitelist.rs", + "item_path": "crate::impl WhitelistData::save_whitelisted_users", + "comment_kind": "OuterDoc", + "comment_text": " Save the current row data in the whitelist json\n", + "comment_hash": "38e34968ad2f79dc8acbaacd57d2ebc1ae8a90be4bff0d0707a72d495f338471", + "body_text": "pub fn save_whitelisted_users(&self, overwrite: bool) {\n let packed_chats = self\n .table\n .get_all_rows()\n .values()\n .filter_map(|row| {\n PackedWhitelistedUser::new(row.row_data.belongs_to, row.row_data.seen_by.clone())\n })\n .collect();\n\n save_whitelisted_users(packed_chats, overwrite);\n }", + "body_hash": "2e28bc82e6ba29d30477b57d3962a25215732534fc622e489e3487d236e923c2" + }, + "src/ui/widgets/card.rs|crate::impl Card::show#free:7c0a2c7b5386": { + "kind": "Free", + "file": "src/ui/widgets/card.rs", + "item_path": "crate::impl Card::show#free:7c0a2c7b5386", + "comment_kind": "Line", + "comment_text": "// Inputs sit on the card color instead of the panel color and lose their\n// contrast, so give idle widgets a visible outline", + "comment_hash": "7c0a2c7b5386ddc4967c0e5286552f49af0d1d0069cbf3a09f167d2ddf0d8e15", + "body_text": "let outline = ui.visuals().widgets.noninteractive.bg_stroke.color;\nui.visuals_mut().widgets.inactive.bg_stroke = Stroke::new(1.0, outline);\nif let Some(title) = self.title {}\nadd_contents(ui)\n}", + "body_hash": "236624078702fc6de46932d5767a01162882a58fdec73e82c475c58a663c5ada" + }, + "src/ui/widgets/card.rs|crate::impl Card::show#free:c56d72b5ed08": { + "kind": "Free", + "file": "src/ui/widgets/card.rs", + "item_path": "crate::impl Card::show#free:c56d72b5ed08", + "comment_kind": "Line", + "comment_text": "// Frames only take the width they need, fill the whole row instead", + "comment_hash": "c56d72b5ed086eac2feb217847dafb550dd4d78a0c469b7543b64b815849281e", + "body_text": "ui.set_width(ui.available_width());", + "body_hash": "c9617b81591d4ac4dfe07d637677414f875c658fdebd3337ef40cc3dab800deb" + }, + "src/ui/widgets/status_line.rs|crate::StatusLine": { + "kind": "Struct", + "file": "src/ui/widgets/status_line.rs", + "item_path": "crate::StatusLine", + "comment_kind": "OuterDoc", + "comment_text": " Single line status text with a colored dot in front. Long text is cut off and the\n\n full text is shown on hover\n", + "comment_hash": "fe1c2e10275f31671ed887a3eea845549afd4f6828177f612f7707f3ffe41637", + "body_text": "pub struct StatusLine {\n text: String,\n dot: Color32,\n width: f32,\n}", + "body_hash": "f86225b6eeb804be2b76d1f79cb84e5c64f0c519f73524a95f36a0ab44e634fc" + }, + "src/ui/widgets/status_line.rs|crate::impl Widget for StatusLine::ui#free:87f06fe96c08": { + "kind": "Free", + "file": "src/ui/widgets/status_line.rs", + "item_path": "crate::impl Widget for StatusLine::ui#free:87f06fe96c08", + "comment_kind": "Line", + "comment_text": "// The full width is reserved up front. Sizing it by its content would make whatever\n// comes next move around every time the text changes", + "comment_hash": "87f06fe96c084ef1db9f04a49be757efb8b4b2975f7628ccba2b38cd52524b2e", + "body_text": "let (rect, response) = ui.allocate_exact_size(size, Sense::hover());\nui.scope_builder(\n UiBuilder::new()\n .max_rect(rect)\n .layout(Layout::left_to_right(Align::Center)),\n |ui| {},\n );\nresponse\n}", + "body_hash": "9acd3f571020db4409a82e63f3507143fee308d87ef2b9f95051ebd33c17bb5e" + }, + "src/ui/widgets/tabs.rs|crate::FADE_TIME": { + "kind": "Const", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::FADE_TIME", + "comment_kind": "OuterDoc", + "comment_text": " Seconds for the hover highlight and the text color to fade\n", + "comment_hash": "5fe7f031ba7cd8c6e6a1c350f50f4681f92aa788d92f82e8114d16ec89d625be", + "body_text": "const FADE_TIME: f32 = 0.15;", + "body_hash": "02b432aa176d203a4da172c6a8f57abd8422b986e145c66d3f068888e2d62692" + }, + "src/ui/widgets/tabs.rs|crate::SLIDE_TIME": { + "kind": "Const", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::SLIDE_TIME", + "comment_kind": "OuterDoc", + "comment_text": " Seconds the selection indicator takes to slide to a new tab\n", + "comment_hash": "c6f5ed9db08166381c2f73f756d6a4a8dd15b2647ca41a5e2bef02eec2d3e900", + "body_text": "const SLIDE_TIME: f64 = 0.22;", + "body_hash": "271c4afe51f5e3b567991250b1aa90f62fb7a8656bb346e58efb36f8a2a1913a" + }, + "src/ui/widgets/tabs.rs|crate::SlideState": { + "kind": "Struct", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::SlideState", + "comment_kind": "OuterDoc", + "comment_text": " Where the indicator was drawn last frame and where it is coming from\n", + "comment_hash": "e09d7fd4d15103a5922c862cf72000b5bcd89c1c5d509401448f8455c5022752", + "body_text": "#[derive(Clone, Copy)]\nstruct SlideState {\n target: usize,\n from: (f32, f32),\n last: (f32, f32),\n started_at: f64,\n}", + "body_hash": "628dba40d79dc24c071f212b46653a353d4f3c5167cf64592d213c5823197183" + }, + "src/ui/widgets/tabs.rs|crate::TabStyle::Pill": { + "kind": "Variant", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::TabStyle::Pill", + "comment_kind": "OuterDoc", + "comment_text": " Plain text with a sliding accent pill behind the selected tab\n", + "comment_hash": "e63cf2f8e18e4905d6ca2d4a12c54c6805c86af8bfe3aa37cbe7e02504b6cce1", + "body_text": "#[default]\nPill", + "body_hash": "e3337be453d354602a9d2379997e37f5a779595d3e2d03286f3baffe30cac89a" + }, + "src/ui/widgets/tabs.rs|crate::TabStyle::Segmented": { + "kind": "Variant", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::TabStyle::Segmented", + "comment_kind": "OuterDoc", + "comment_text": " Items inside a rounded track with a sliding pill behind the selected one\n", + "comment_hash": "64e491db66ee33f6d9f60a8a9b4d2c16bb4b007a97ccc814f582967d52455424", + "body_text": "Segmented", + "body_hash": "5caaf62a4b6abb7a38289c4c2dac04188c1cd4ac14a275110311d11dc6f843f3" + }, + "src/ui/widgets/tabs.rs|crate::Tabs": { + "kind": "Struct", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::Tabs", + "comment_kind": "OuterDoc", + "comment_text": " Animated row of mutually exclusive tabs.\n", + "comment_hash": "52207d3e1607f26d24ecb92ba6e751ab064779b7566160f04ac28bd961a1c15a", + "body_text": "pub struct Tabs {\n id_salt: &'static str,\n items: Vec,\n selected: usize,\n style: TabStyle,\n min_item_width: f32,\n equal_width: bool,\n centered: bool,\n hover_text: Option>,\n}", + "body_hash": "0fb887246c88f6061e3a77abb32f3730e191924656d6c76a81906bd1ce254480" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::centered": { + "kind": "Function", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::centered", + "comment_kind": "OuterDoc", + "comment_text": " Center the strip in the row it is placed in. It never moves left of where it\n\n would start otherwise, so widgets placed before it are not overlapped\n", + "comment_hash": "a11796a080ed37c6a2affacdfea9155205c155fee5aead116d0850ce8f8bc6e1", + "body_text": "pub fn centered(mut self, centered: bool) -> Self {\n self.centered = centered;\n self\n }", + "body_hash": "6cfdf0bd6bbd25883c4fd02e0e3c36afbd3a68cc92f8b3e0b19f9c9923c843fa" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::equal_width": { + "kind": "Function", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::equal_width", + "comment_kind": "OuterDoc", + "comment_text": " Give every item the width of the widest one\n", + "comment_hash": "4b99445243355c50f3e402a01297e960ef4e29106c702e953ec6ba02a33246bc", + "body_text": "pub fn equal_width(mut self, equal: bool) -> Self {\n self.equal_width = equal;\n self\n }", + "body_hash": "13b05624a14f8d9b0703933481c1e01652dccedd9769d2a2878aa9ab74511c18" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::hover_text": { + "kind": "Function", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::hover_text", + "comment_kind": "OuterDoc", + "comment_text": " Tooltip shown when hovering an item\n", + "comment_hash": "4da0a884bf21321195bc50330582e031b943f29891479cc6785a6bf43c88a886", + "body_text": "pub fn hover_text(mut self, hover_text: impl Fn(&T) -> String + 'static) -> Self {\n self.hover_text = Some(Box::new(hover_text));\n self\n }", + "body_hash": "6d46e8b14dd84c153782738156beae7fc8c9432e8bc6be9a5d6bb9450f0934a0" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show": { + "kind": "Function", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show", + "comment_kind": "OuterDoc", + "comment_text": " Draws the tabs and returns the item that was clicked this frame\n", + "comment_hash": "7424cb73592a753740d45c81d477efad6c7cfd471f3db0caacdc539519e1a1ae", + "body_text": "pub fn show(self, ui: &mut Ui) -> Option {\n let Self {\n id_salt,\n mut items,\n selected,\n style,\n min_item_width,\n equal_width,\n centered,\n hover_text,\n } = self;\n\n if items.is_empty() {\n return None;\n }\n\n let id = ui.make_persistent_id(id_salt);\n let pad_x = match style {\n TabStyle::Pill => 14.0,\n TabStyle::Segmented => 10.0,\n };\n let height = ui.spacing().interact_size.y + 4.0;\n let font = TextStyle::Button.resolve(ui.style());\n\n \n let galleys: Vec<_> = items\n .iter()\n .map(|item| {\n ui.painter()\n .layout_no_wrap(item.to_string(), font.clone(), Color32::PLACEHOLDER)\n })\n .collect();\n\n let widest = galleys\n .iter()\n .map(|galley| galley.size().x)\n .fold(0.0, f32::max);\n\n let widths: Vec = galleys\n .iter()\n .map(|galley| {\n let text_width = if equal_width { widest } else { galley.size().x };\n (text_width + pad_x * 2.0).max(min_item_width)\n })\n .collect();\n\n \n let (inset_x, inset_y) = match style {\n TabStyle::Segmented => (3.0, 3.0),\n TabStyle::Pill => (0.0, 2.0),\n };\n let total_width = widths.iter().sum::() + inset_x * 2.0;\n\n let (mut strip, _) = ui.allocate_exact_size(vec2(total_width, height), Sense::hover());\n\n if centered {\n let row = ui.max_rect();\n let target_left = row.center().x - total_width / 2.0;\n let max_shift = (row.right() - strip.right()).max(0.0);\n let shift = (target_left - strip.left()).clamp(0.0, max_shift);\n strip = strip.translate(vec2(shift, 0.0));\n }\n\n let mut x = strip.left() + inset_x;\n let rects: Vec = widths\n .iter()\n .map(|width| {\n let rect = Rect::from_min_size(\n pos2(x, strip.top() + inset_y),\n Vec2::new(*width, height - inset_y * 2.0),\n );\n x += width;\n rect\n })\n .collect();\n\n \n let mut clicked = None;\n let mut responses: Vec = Vec::with_capacity(items.len());\n for (i, rect) in rects.iter().enumerate() {\n let response = ui\n .interact(*rect, id.with((\"item\", i)), Sense::click())\n .on_hover_cursor(CursorIcon::PointingHand);\n\n let response = match &hover_text {\n Some(hover_text) => response.on_hover_text(hover_text(&items[i])),\n None => response,\n };\n\n let label = items[i].to_string();\n response.widget_info(|| {\n WidgetInfo::selected(Role::Tab, ui.is_enabled(), i == selected, &label)\n });\n\n if response.clicked() {\n clicked = Some(i);\n }\n responses.push(response);\n }\n\n if !ui.is_rect_visible(strip) {\n return clicked.map(|i| items.swap_remove(i));\n }\n\n let visuals = ui.visuals().clone();\n let accent = visuals.selection.bg_fill;\n let ctx = ui.ctx().clone();\n\n let (track_radius, pill_radius) = (CornerRadius::same(7), CornerRadius::same(5));\n\n match style {\n \n TabStyle::Pill => {}\n TabStyle::Segmented => {\n ui.painter()\n .rect_filled(strip, track_radius, visuals.extreme_bg_color);\n ui.painter().rect_stroke(\n strip,\n track_radius,\n visuals.widgets.noninteractive.bg_stroke,\n StrokeKind::Inside,\n );\n }\n }\n\n \n for (i, response) in responses.iter().enumerate() {\n let hover_t = ctx.animate_bool_with_time(\n id.with((\"hover\", i)),\n response.hovered() && i != selected,\n FADE_TIME,\n );\n if hover_t > 0.0 {\n let color = visuals.widgets.hovered.weak_bg_fill.gamma_multiply(hover_t);\n ui.painter().rect_filled(rects[i], pill_radius, color);\n }\n }\n\n \n let now = ctx.input(|i| i.time);\n let target = rects[selected];\n \n \n let origin = strip.left();\n let target_x = (target.left() - origin, target.right() - origin);\n\n let mut state = ctx\n .data_mut(|d| d.get_temp::(id))\n .unwrap_or(SlideState {\n target: selected,\n from: target_x,\n last: target_x,\n started_at: now - SLIDE_TIME,\n });\n\n if state.target != selected {\n state.from = state.last;\n state.target = selected;\n state.started_at = now;\n }\n\n let progress = (((now - state.started_at) / SLIDE_TIME) as f32).clamp(0.0, 1.0);\n let eased = ease_out_cubic(progress);\n let left = lerp(state.from.0, target_x.0, eased);\n let right = lerp(state.from.1, target_x.1, eased);\n state.last = (left, right);\n let (left, right) = (left + origin, right + origin);\n\n if progress < 1.0 {\n ctx.request_repaint();\n }\n ctx.data_mut(|d| d.insert_temp(id, state));\n\n let pill = Rect::from_min_max(pos2(left, target.top()), pos2(right, target.bottom()));\n ui.painter().rect_filled(pill, pill_radius, accent);\n\n \n let idle = visuals.widgets.inactive.fg_stroke.color;\n let hovered = visuals.widgets.hovered.fg_stroke.color;\n let selected_color = visuals.selection.stroke.color;\n\n for (i, (galley, rect)) in galleys.into_iter().zip(&rects).enumerate() {\n let select_t =\n ctx.animate_bool_with_time(id.with((\"select\", i)), i == selected, FADE_TIME);\n let hover_t = ctx.animate_bool_with_time(\n id.with((\"text_hover\", i)),\n responses[i].hovered(),\n FADE_TIME,\n );\n\n let color = idle\n .lerp_to_gamma(hovered, hover_t)\n .lerp_to_gamma(selected_color, select_t);\n\n let text_pos = rect.center() - galley.size() / 2.0;\n ui.painter()\n .galley_with_override_text_color(text_pos, galley, color);\n }\n\n clicked.map(|i| items.swap_remove(i))\n }", + "body_hash": "ffe4d89c01b37895194a33e0b38e81f1a09ef8f7185e73410516f0756a693ae4" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show#free:180b6dc3a6c4": { + "kind": "Free", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show#free:180b6dc3a6c4", + "comment_kind": "Line", + "comment_text": "// Relative to the strip so the indicator does not slide when the strip itself moves,\n// for example when the window is resized by switching tabs", + "comment_hash": "180b6dc3a6c46fbbeadbb75f895f0264d5167e344ba54c29b5c9234a576e1d71", + "body_text": "let origin = strip.left();\nlet target_x = (target.left() - origin, target.right() - origin);\nlet mut state = ctx\n .data_mut(|d| d.get_temp::(id))\n .unwrap_or(SlideState {\n target: selected,\n from: target_x,\n last: target_x,\n started_at: now - SLIDE_TIME,\n });\nif state.target != selected {}\nlet progress = (((now - state.started_at) / SLIDE_TIME) as f32).clamp(0.0, 1.0);\nlet eased = ease_out_cubic(progress);\nlet left = lerp(state.from.0, target_x.0, eased);\nlet right = lerp(state.from.1, target_x.1, eased);\nstate.last = (left, right);\nlet (left, right) = (left + origin, right + origin);\nif progress < 1.0 {}\nctx.data_mut(|d| d.insert_temp(id, state));\nlet pill = Rect::from_min_max(pos2(left, target.top()), pos2(right, target.bottom()));\nui.painter().rect_filled(pill, pill_radius, accent);", + "body_hash": "911760985d2fa509aea4021c4cdf4f90ce12a0f5c2da581acedcdefdd121dcf8" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show#free:1a3cf0ed240d": { + "kind": "Free", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show#free:1a3cf0ed240d", + "comment_kind": "Line", + "comment_text": "// Hover highlight fades in and out on each item independently", + "comment_hash": "1a3cf0ed240dd517f1e8bdcd074e5539c8d8e94f5d957a8915597f5b6a3fd04f", + "body_text": "for (i, response) in responses.iter().enumerate() {}", + "body_hash": "62c2dc55a2df2a5a4214e359170db0113034ed23c91699ceaec70d4cca62d402" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show#free:4ef08302873e": { + "kind": "Free", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show#free:4ef08302873e", + "comment_kind": "Line", + "comment_text": "// Text color is overridden at paint time so it can fade between states", + "comment_hash": "4ef08302873eab58289a391182f94b99b6b57b16f03be3751a7c285310158e37", + "body_text": "let galleys: Vec<_> = items\n .iter()\n .map(|item| {})\n .collect();\nlet widest = galleys\n .iter()\n .map(|galley| galley.size().x)\n .fold(0.0, f32::max);\nlet widths: Vec = galleys\n .iter()\n .map(|galley| {})\n .collect();", + "body_hash": "ab5c27658d568ee8019129f9aa1a4df3e75fa1fa399b5332dcd6926ec3cafc8e" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show#free:6c73065880b5": { + "kind": "Free", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show#free:6c73065880b5", + "comment_kind": "Line", + "comment_text": "// Text fades between its idle, hovered and selected colors", + "comment_hash": "6c73065880b59866a9b8a6bc8df7b2a47936d837de75bceea4549fb672fdda77", + "body_text": "let idle = visuals.widgets.inactive.fg_stroke.color;\nlet hovered = visuals.widgets.hovered.fg_stroke.color;\nlet selected_color = visuals.selection.stroke.color;\nfor (i, (galley, rect)) in galleys.into_iter().zip(&rects).enumerate() {}\nclicked.map(|i| items.swap_remove(i))\n}", + "body_hash": "0dc6f6f4d8d36a34c52dba3b858cf1f1c46d74459a09d64326012de10f398a8a" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show#free:82a9de78187c": { + "kind": "Free", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show#free:82a9de78187c", + "comment_kind": "Line", + "comment_text": "// Slide the indicator from where it was last drawn to the selected item", + "comment_hash": "82a9de78187c0b8f0ba0e05accf297234d75b59e2e2c280b033b359615aba8bd", + "body_text": "let now = ctx.input(|i| i.time);\nlet target = rects[selected];", + "body_hash": "9855caa2d10181b151c5266daddfe511aed5f7a3e4e96b7c392f24138c7417b3" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show#free:d03fa567741b": { + "kind": "Free", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show#free:d03fa567741b", + "comment_kind": "Line", + "comment_text": "// Interaction first, painting afterwards, since the indicator is drawn under the text", + "comment_hash": "d03fa567741ba2b45393a7a8e0286e568057fce309182f6f4ef23e558da673a5", + "body_text": "let mut clicked = None;\nlet mut responses: Vec = Vec::with_capacity(items.len());\nfor (i, rect) in rects.iter().enumerate() {}\nif !ui.is_rect_visible(strip) {}\nlet visuals = ui.visuals().clone();\nlet accent = visuals.selection.bg_fill;\nlet ctx = ui.ctx().clone();\nlet (track_radius, pill_radius) = (CornerRadius::same(7), CornerRadius::same(5));\nmatch style {\n \n TabStyle::Pill => {}\n TabStyle::Segmented => {}\n }", + "body_hash": "dce249e2c1980ca0a622a6af1dd570c9fe5ef006ccb925155c37d4906c5068c2" + }, + "src/ui/widgets/tabs.rs|crate::impl Tabs::show#free:f6abe541c5f8": { + "kind": "Free", + "file": "src/ui/widgets/tabs.rs", + "item_path": "crate::impl Tabs::show#free:f6abe541c5f8", + "comment_kind": "Line", + "comment_text": "// The segmented track has a small inset so the pill does not touch the border", + "comment_hash": "f6abe541c5f8b92c99aa420c5383eaa7d51da65f41fb0a47e2609235fa391403", + "body_text": "let (inset_x, inset_y) = match style {\n TabStyle::Segmented => (3.0, 3.0),\n TabStyle::Pill => (0.0, 2.0),\n };\nlet total_width = widths.iter().sum::() + inset_x * 2.0;\nlet (mut strip, _) = ui.allocate_exact_size(vec2(total_width, height), Sense::hover());\nif centered {}\nlet mut x = strip.left() + inset_x;\nlet rects: Vec = widths\n .iter()\n .map(|width| {})\n .collect();", + "body_hash": "8965a8a90f28fcb9e1295da070a2ebbd74557c197a7eaacd3e3dece27c9ec6d0" + }, + "src/utils/chat_link.rs|crate::chat_to_text": { + "kind": "Function", + "file": "src/utils/chat_link.rs", + "item_path": "crate::chat_to_text", + "comment_kind": "OuterDoc", + "comment_text": " Convert inserted chat points into textual representation\n", + "comment_hash": "9fd25b3772e6eb66239fe1bfa0b7256f118f54dcefab0ae8e062dbabe7d8b2ec", + "body_text": "pub fn chat_to_text(start: &str, end: &str) -> String {\n let chat_data: BTreeMap =\n parse_chat_details(start, end).into_iter().collect();\n\n let mut text_data = \"Detected Chats:\".to_string();\n\n for (name, parsed) in chat_data {\n let mut chat_text = format!(\" {name}\");\n\n if let Some(end_point) = parsed.end_point() {\n let _ = write!(chat_text, \": {end_point} - \");\n\n if let Some(start_point) = parsed.start_point() {\n let _ = write!(chat_text, \"{start_point}\");\n } else {\n chat_text += \"∞\";\n }\n } else if let Some(start_point) = parsed.start_point() {\n chat_text += \": 1 - \";\n let _ = write!(chat_text, \"{start_point}\");\n } else {\n chat_text += \": ∞\";\n }\n let _ = write!(text_data, \" {chat_text}\");\n }\n\n text_data\n}", + "body_hash": "261bb96b0c1e5f9e6e76254e3e060b1bc318711b5490808daae9520f62b15048" + }, + "src/utils/chat_link.rs|crate::parse_chat_details": { + "kind": "Function", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_chat_details", + "comment_kind": "OuterDoc", + "comment_text": " Parse start and end point strings as parsed chat points\n", + "comment_hash": "f8e287a4446cc38735f0e9b4170e5a2fcf9e86db25fba5466acf196ce04d5d0e", + "body_text": "pub fn parse_chat_details(start: &str, end: &str) -> HashMap {\n let start_chat_list: Vec<&str> = start.split_whitespace().collect();\n let end_chat_list: Vec<&str> = end.split_whitespace().collect();\n\n let mut parsed_chat_list = HashMap::new();\n\n for chat in start_chat_list {\n let (name, num) = parse_tg_chat(chat);\n if name.is_none() {\n error!(\"{chat} is getting ignored as no chat name was found\");\n continue;\n }\n\n let name = name.unwrap();\n let parsed = ParsedChat::new(name.clone(), num, None);\n parsed_chat_list.insert(name, parsed);\n }\n\n for chat in end_chat_list {\n let (name, num) = parse_tg_chat(chat);\n if name.is_none() {\n error!(\"{chat} is getting ignored as no chat name was found\");\n continue;\n }\n\n let name = name.unwrap();\n if let Some(parsed) = parsed_chat_list.get_mut(&name) {\n if let Some(end_num) = num {\n let completed = parsed.set_end_point(end_num);\n if !completed {\n error!(\n \"End point cannot be equal or bigger than start point. Ignoring the end point for {chat}\"\n );\n }\n }\n } else {\n error!(\"{chat} was not found in the start point, this will be ignored\");\n }\n }\n\n parsed_chat_list\n}", + "body_hash": "7365fcebcb9d3319ed9c9ff89956afc2eba7482b91ddd1a3f4055a0d4adb3827" + }, + "src/utils/chat_link.rs|crate::parse_tg_chat": { + "kind": "Function", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_tg_chat", + "comment_kind": "OuterDoc", + "comment_text": " Tries to parse a link to get the chat name and the message ID\n", + "comment_hash": "3317aba8ee31c60b372beadee3f44bfe60117752f68f1e51d683c45a66009fd6", + "body_text": "pub fn parse_tg_chat(text: &str) -> (Option, Option) {\n if text.is_empty() {\n return (None, None);\n }\n\n let mut chat_name = None;\n let mut message_number = None;\n\n \n if text.contains(\"t.me\") {\n \n let split_text = text.split_once(\"t.me/\");\n if let Some((_first, second)) = split_text {\n \n \n \n if second.contains('/') {\n (chat_name, message_number) = split_tg_link(second);\n } else {\n chat_name = Some(second.to_string());\n }\n }\n } else if text.starts_with('@') {\n \n let split_text = text.split_once('@');\n \n if let Some((_first, second)) = split_text {\n if second.contains('/') {\n (chat_name, message_number) = split_tg_link(second);\n } else if !second.is_empty() {\n chat_name = Some(second.to_string());\n }\n }\n } else {\n \n if text.contains('/') {\n (chat_name, message_number) = split_tg_link(text);\n } else {\n chat_name = Some(text.to_string());\n }\n }\n (chat_name, message_number)\n}", + "body_hash": "00949401e42f86e18dd8290303954d78e3864a778af23c99af6a0386b2326268" + }, + "src/utils/chat_link.rs|crate::parse_tg_chat#free:2424f16f1713": { + "kind": "Free", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_tg_chat#free:2424f16f1713", + "comment_kind": "Line", + "comment_text": "// split expected result t.me and chat_name/1234", + "comment_hash": "2424f16f171397422977bcbf264b20e328dce00f7b546723f3c1b21a9ce30e83", + "body_text": "let split_text = text.split_once(\"t.me/\");\nif let Some((_first, second)) = split_text {}\n}", + "body_hash": "c6f569ce3a939aec1bd4d92df6011d790b66e811399422f669d9e4bc51d4895f" + }, + "src/utils/chat_link.rs|crate::parse_tg_chat#free:38667e28fb39": { + "kind": "Free", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_tg_chat#free:38667e28fb39", + "comment_kind": "Line", + "comment_text": "// // split expected result @ and chat_name/1234", + "comment_hash": "38667e28fb3902cf831be21bc8f90566a09322a6b77aab3d560ac512885cbb7a", + "body_text": "if let Some((_first, second)) = split_text {}\n}", + "body_hash": "efc345819be67c01ff43ec0575a52e498c25d8b9c46dd356a7f8cc2ef025f9f8" + }, + "src/utils/chat_link.rs|crate::parse_tg_chat#free:62f92174c8a5": { + "kind": "Free", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_tg_chat#free:62f92174c8a5", + "comment_kind": "Line", + "comment_text": "// Example chat_name. If invalid, it will still be caught here, later will get verified by the telegram side", + "comment_hash": "62f92174c8a57ba72808e73ea9222286a4d586e083030b35a6d28cbf30cd7ef9", + "body_text": "if text.contains('/') {} else {}\n}", + "body_hash": "c1e2654b223584527acdf9d414312a4f43256202e38e88c3c05da6cc2bb968ed" + }, + "src/utils/chat_link.rs|crate::parse_tg_chat#free:6a651374c2be": { + "kind": "Free", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_tg_chat#free:6a651374c2be", + "comment_kind": "Line", + "comment_text": "// It will be either chat_name/number or chat_name\n// if chat_name/number split it again and get the number\n// otherwise set whatever value is remaining as the parsed chat name", + "comment_hash": "6a651374c2be11d9228edd2e0b84eb5d089a1c2c959f00a37459626153c01b7b", + "body_text": "if second.contains('/') {} else {}\n}", + "body_hash": "fed7f3a2b5ce73a98c2cc0a8ab19f7acf04084a8b909e14f90d6ffa72ac45316" + }, + "src/utils/chat_link.rs|crate::parse_tg_chat#free:792dbf3e331b": { + "kind": "Free", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_tg_chat#free:792dbf3e331b", + "comment_kind": "Line", + "comment_text": "// Example @chat_name/1234", + "comment_hash": "792dbf3e331baf537c879fc50473efa5bd6ef4b36762731355a5e4f9c371b73c", + "body_text": "let split_text = text.split_once('@');", + "body_hash": "7c438b1b9fb5b0ac2c64b649879df6c14cbef93e59b519dbf867c1776ed12edd" + }, + "src/utils/chat_link.rs|crate::parse_tg_chat#free:925dc6824d2f": { + "kind": "Free", + "file": "src/utils/chat_link.rs", + "item_path": "crate::parse_tg_chat#free:925dc6824d2f", + "comment_kind": "Line", + "comment_text": "// Example t.me/chat_name/1234", + "comment_hash": "925dc6824d2f22c689253693d3614e958187726204bd7c628d372d75d9bea1f5", + "body_text": "if text.contains(\"t.me\") {} else if text.starts_with('@') {} else {}\n(chat_name, message_number)\n}", + "body_hash": "84b8ab5e7644dc51950125d751b7cf9df93c0afa59b5e6b383023e88b1641215" + }, + "src/utils/chat_link.rs|crate::split_tg_link": { + "kind": "Function", + "file": "src/utils/chat_link.rs", + "item_path": "crate::split_tg_link", + "comment_kind": "OuterDoc", + "comment_text": " Splits a string on slash and tries to get the tg chat name and message number\n", + "comment_hash": "29ce6e94eddb1fc628e9e2a334860c86816a6413eebb43860a6a434171631a48", + "body_text": "fn split_tg_link(text: &str) -> (Option, Option) {\n let mut chat_name = None;\n let mut message_number = None;\n\n if let Some((name, num)) = text.split_once('/') {\n chat_name = Some(name.to_string());\n if let Ok(num) = num.parse() {\n message_number = Some(num);\n }\n }\n\n (chat_name, message_number)\n}", + "body_hash": "fc760cf583bf19180c2757012516049da569b13fe716c75e2464a82b9d531e5e" + }, + "src/utils/format.rs|crate::entry_insert_user": { + "kind": "Function", + "file": "src/utils/format.rs", + "item_path": "crate::entry_insert_user", + "comment_kind": "OuterDoc", + "comment_text": " Checks for a value in the `HashMap` of a `HashMap`\n", + "comment_hash": "994c26380bc712dd5554c0e1ee6b176cc6510ea37c717b97018f0129732da3e5", + "body_text": "pub fn entry_insert_user(\n user_data: &mut HashMap>,\n user_row_data: UserRowData,\n id: i64,\n date: NaiveDate,\n) {\n let entry = user_data.entry(date).or_default();\n entry.entry(id).or_insert(user_row_data.clone());\n}", + "body_hash": "b88cfed14843f3592254bfcdebe78ac3794079267d0fa7e31e55686717d16b61" + }, + "src/utils/format.rs|crate::theme_hover_text": { + "kind": "Function", + "file": "src/utils/format.rs", + "item_path": "crate::theme_hover_text", + "comment_kind": "OuterDoc", + "comment_text": " Returns the proper emoji based on light or dark value\n", + "comment_hash": "8e00f3c319076ff47f82a584b2b4d34f5e6904556f1591e12b42534ca7eefafe", + "body_text": "pub fn theme_hover_text(is_light_theme: bool) -> String {\n if is_light_theme {\n \"Switch to dark theme\".to_string()\n } else {\n \"Switch to light theme\".to_string()\n }\n}", + "body_hash": "cf23b881746f5bdfc241cdbbe81dbf89dc257ca06acad912b74fe002eccccddd" + }, + "src/utils/format.rs|crate::time_to_string": { + "kind": "Function", + "file": "src/utils/format.rs", + "item_path": "crate::time_to_string", + "comment_kind": "OuterDoc", + "comment_text": " Convenient function to format `NaiveDateTime` to string. Used for the Chart UI\n", + "comment_hash": "fa437ea0aa262393d13bdad6bfebf8dbdf93b46416fbbf825f4a4805eac65559", + "body_text": "pub fn time_to_string(time: &NaiveDateTime, timing: ChartTiming) -> String {\n match timing {\n ChartTiming::Hourly => time.to_string(),\n _ => time.format(\"%Y-%m-%d\").to_string(),\n }\n}", + "body_hash": "0e32a24a3d777d2d2f012f40a96d9d7341961128f04dac22b5802f02bd6dad1f" + }, + "src/utils/format.rs|crate::weekday_num_to_string": { + "kind": "Function", + "file": "src/utils/format.rs", + "item_path": "crate::weekday_num_to_string", + "comment_kind": "OuterDoc", + "comment_text": " Convenient function to convert u8 to a Week name string. used for the Chart UI\n", + "comment_hash": "de8761d18914cbcbb69e6897f25226a46559d7cd51334fcc56fa868c56ba0eb5", + "body_text": "pub fn weekday_num_to_string(weekday: u8) -> String {\n match weekday {\n 0 => String::from(\"Monday\"),\n 1 => String::from(\"Tuesday\"),\n 2 => String::from(\"Wednesday\"),\n 3 => String::from(\"Thursday\"),\n 4 => String::from(\"Friday\"),\n 5 => String::from(\"Saturday\"),\n 6 => String::from(\"Sunday\"),\n _ => unreachable!(),\n }\n}", + "body_hash": "63d8d550844f486ee1c728aa4b47321177ba756e9eb385bb29507631fc80c463" + }, + "src/utils/runtime.rs|crate::get_runtime": { + "kind": "Function", + "file": "src/utils/runtime.rs", + "item_path": "crate::get_runtime", + "comment_kind": "OuterDoc", + "comment_text": " Convenient tokio runtime getter\n", + "comment_hash": "d661cef44f0310c99f46feb97906ccffc94926364218045ea8ecf9d4af387f5b", + "body_text": "pub fn get_runtime() -> Runtime {\n runtime::Builder::new_multi_thread()\n .worker_threads(99)\n .enable_all()\n .build()\n .unwrap()\n}", + "body_hash": "908c02647aadb1a67f0e04357c17d23439f07585070a62d4ec3fd2ce1a2e70af" + }, + "src/utils/storage.rs|crate::find_session_files": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::find_session_files", + "comment_kind": "OuterDoc", + "comment_text": " Finds all the saved session files\n", + "comment_hash": "cb82601a274f2c09e8f7ed545a04124b6eb17bd11be05fb7db00c9e9de45ee77", + "body_text": "pub fn find_session_files() -> Vec {\n let mut sessions = Vec::new();\n if let Ok(entries) = fs::read_dir(\".\") {\n for entry in entries {\n if let Ok(file_name) = entry.unwrap().file_name().into_string()\n && file_name.ends_with(\".sqlite\")\n {\n info!(\"Found existing session file {file_name}\");\n sessions.push(file_name);\n }\n }\n }\n sessions\n}", + "body_hash": "78da97cbc412282d6b60a8faec76278276b9f59472dc02ddec65c974f627d31e" + }, + "src/utils/storage.rs|crate::get_api_keys": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::get_api_keys", + "comment_kind": "OuterDoc", + "comment_text": " Tries to read the API key json file\n", + "comment_hash": "4fb6cf33b6bcbed6817c32f176eb45e084771a0faeab35e77de53e0e1dfa5545", + "body_text": "pub fn get_api_keys() -> Option {\n let mut to_return = None;\n let mut api_key_path = PathBuf::from(\".\");\n api_key_path.push(\"api_keys.json\");\n\n let file = File::open(api_key_path);\n\n if let Ok(mut file) = file {\n let mut contents = String::new();\n file.read_to_string(&mut contents)\n .expect(\"Failed to read file\");\n\n let result = serde_json::from_str::(&contents);\n if let Ok(result) = result\n && !result.api_id.is_empty()\n && !result.api_hash.is_empty()\n {\n to_return = Some(result);\n }\n }\n\n to_return\n}", + "body_hash": "1b3fdd57c01d45dac63da00fb1319545e3b542c88a257489a27ce8e51353178c" + }, + "src/utils/storage.rs|crate::get_blacklisted": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::get_blacklisted", + "comment_kind": "OuterDoc", + "comment_text": " Reads the blacklisted user `PeerRef` values and returns them\n", + "comment_hash": "8892512cf72e8677d20b9dc1a52e80dbcaf83f1c1574dced3a2556eaf08a2c99", + "body_text": "pub fn get_blacklisted() -> Result, Box> {\n let mut blacklist_path = PathBuf::from(\".\");\n blacklist_path.push(BLACKLIST_FILE);\n\n let file = File::open(blacklist_path);\n\n if let Ok(mut file) = file {\n let mut contents = String::new();\n file.read_to_string(&mut contents)?;\n let users = serde_json::from_str(&contents)?;\n Ok(users)\n } else {\n Ok(Vec::new())\n }\n}", + "body_hash": "22e06c0a5957a75a6488f08d73d959f6ef0401f06a91cb4b07dd3d85593dd77a" + }, + "src/utils/storage.rs|crate::get_font_data": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::get_font_data", + "comment_kind": "OuterDoc", + "comment_text": " Tries to find and read the Font files\n", + "comment_hash": "11243d10033bb7f235f7cad43668e260134302b03d8823bc9d3e2a748f0bb6c0", + "body_text": "pub fn get_font_data() -> Option<(Vec, Vec)> {\n let mut gentium_font = PathBuf::from(\".\");\n let mut cjk_font = PathBuf::from(\".\");\n\n gentium_font.push(\"fonts\");\n cjk_font.push(\"fonts\");\n fs::create_dir_all(&gentium_font).unwrap();\n\n gentium_font.push(\"GentiumBookPlus-Regular.ttf\");\n cjk_font.push(\"NotoSansCJK-Regular.ttc\");\n\n let mut gentium_font_data = Vec::new();\n let mut cjk_font_data = Vec::new();\n\n if let Ok(mut file) = File::open(gentium_font) {\n file.read_to_end(&mut gentium_font_data)\n .expect(\"Failed to read file\");\n } else {\n return None;\n }\n\n if let Ok(mut file) = File::open(cjk_font) {\n file.read_to_end(&mut cjk_font_data)\n .expect(\"Failed to read file\");\n } else {\n return None;\n }\n\n Some((cjk_font_data, gentium_font_data))\n}", + "body_hash": "7b4fa87865ecf8f1ccc350c8e8b5df6e3a4f65de85d43c374e1435be31d02676" + }, + "src/utils/storage.rs|crate::get_whitelisted": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::get_whitelisted", + "comment_kind": "OuterDoc", + "comment_text": " Reads the whitelisted user `PeerRef` values and returns them\n", + "comment_hash": "782ff241258dfd478ddb79da1b916f39ac7e8cd146e41fa1be244e9c17982c9c", + "body_text": "pub fn get_whitelisted() -> Result, Box> {\n let mut whitelist_path = PathBuf::from(\".\");\n whitelist_path.push(WHITELIST_FILE);\n\n let file = File::open(whitelist_path);\n\n if let Ok(mut file) = file {\n let mut contents = String::new();\n file.read_to_string(&mut contents)?;\n let users = serde_json::from_str(&contents)?;\n Ok(users)\n } else {\n Ok(Vec::new())\n }\n}", + "body_hash": "3cfb3543218c80357fc9145a77d8784b116114319c5184e7da21b93a904b5858" + }, + "src/utils/storage.rs|crate::save_api_keys": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::save_api_keys", + "comment_kind": "OuterDoc", + "comment_text": " Saves the API keys in a json file\n", + "comment_hash": "01e5fa26847e5ddd9769d5984447f759c691f7140094d4b3ba8b1f49349da484", + "body_text": "pub fn save_api_keys(api_keys: &TGKeys) {\n let data = serde_json::to_string(api_keys);\n\n if let Ok(data) = data {\n let mut api_key_path = PathBuf::from(\".\");\n api_key_path.push(\"api_keys.json\");\n let mut file = File::create(api_key_path).unwrap();\n file.write_all(data.as_bytes()).unwrap();\n }\n}", + "body_hash": "e10eef002a47c975b1e274b1cb7d978141d432973a5f6446b271b42e8470bc85" + }, + "src/utils/storage.rs|crate::save_blacklisted_users": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::save_blacklisted_users", + "comment_kind": "OuterDoc", + "comment_text": " Saves `PeerRef` values to a json file\n", + "comment_hash": "4683219471a2250b9128bac29e3cf346f9c3ead3f6db15bd0632c18a2c1e934e", + "body_text": "pub fn save_blacklisted_users(packed_chats: Vec, overwrite: bool) {\n \n let mut existing_data = HashSet::new();\n\n let mut whitelist_path = PathBuf::from(\".\");\n whitelist_path.push(BLACKLIST_FILE);\n\n let file = File::open(&whitelist_path);\n\n if !overwrite && let Ok(mut file) = file {\n let mut contents = String::new();\n file.read_to_string(&mut contents)\n .expect(\"Failed to read file\");\n\n existing_data = serde_json::from_str(&contents).unwrap();\n }\n\n existing_data.extend(packed_chats);\n\n let data = serde_json::to_string(&existing_data).unwrap();\n\n let mut file = File::create(whitelist_path).unwrap();\n file.write_all(data.as_bytes()).unwrap();\n}", + "body_hash": "721e46e57d9d9e3d89feb323daf004b296e6b45b324483398744ff8d3f4660d2" + }, + "src/utils/storage.rs|crate::save_blacklisted_users#free:b70d684532c6": { + "kind": "Free", + "file": "src/utils/storage.rs", + "item_path": "crate::save_blacklisted_users#free:b70d684532c6", + "comment_kind": "Line", + "comment_text": "// HashSet to avoid duplicate whitelisted users", + "comment_hash": "b70d684532c62dd5061022dd55af52569499c2831f6d89a047ca8827c5c13716", + "body_text": "let mut existing_data = HashSet::new();\nlet mut whitelist_path = PathBuf::from(\".\");\nwhitelist_path.push(BLACKLIST_FILE);\nlet file = File::open(&whitelist_path);\nif !overwrite && let Ok(mut file) = file {}\nexisting_data.extend(packed_chats);\nlet data = serde_json::to_string(&existing_data).unwrap();\nlet mut file = File::create(whitelist_path).unwrap();\nfile.write_all(data.as_bytes()).unwrap();\n}", + "body_hash": "0fed657f8e3ed039a4d06f2294f37a8bdfd78adddd074b108fe3e6cc6782b5da" + }, + "src/utils/storage.rs|crate::save_whitelisted_users": { + "kind": "Function", + "file": "src/utils/storage.rs", + "item_path": "crate::save_whitelisted_users", + "comment_kind": "OuterDoc", + "comment_text": " Saves `PeerRef` values to a json file\n", + "comment_hash": "4683219471a2250b9128bac29e3cf346f9c3ead3f6db15bd0632c18a2c1e934e", + "body_text": "pub fn save_whitelisted_users(packed_chats: Vec, overwrite: bool) {\n \n let mut existing_data = HashSet::new();\n\n let mut whitelist_path = PathBuf::from(\".\");\n whitelist_path.push(WHITELIST_FILE);\n\n let file = File::open(&whitelist_path);\n\n if !overwrite && let Ok(mut file) = file {\n let mut contents = String::new();\n file.read_to_string(&mut contents)\n .expect(\"Failed to read file\");\n\n existing_data = serde_json::from_str(&contents).unwrap();\n }\n\n existing_data.extend(packed_chats);\n\n let data = serde_json::to_string(&existing_data).unwrap();\n\n let mut file = File::create(whitelist_path).unwrap();\n file.write_all(data.as_bytes()).unwrap();\n}", + "body_hash": "f8cf57b82a368ba8fed3bcfbb7ecc6077b48f92ce010116a8139e2f4d05891ec" + }, + "src/utils/storage.rs|crate::save_whitelisted_users#free:b70d684532c6": { + "kind": "Free", + "file": "src/utils/storage.rs", + "item_path": "crate::save_whitelisted_users#free:b70d684532c6", + "comment_kind": "Line", + "comment_text": "// HashSet to avoid duplicate whitelisted users", + "comment_hash": "b70d684532c62dd5061022dd55af52569499c2831f6d89a047ca8827c5c13716", + "body_text": "let mut existing_data = HashSet::new();\nlet mut whitelist_path = PathBuf::from(\".\");\nwhitelist_path.push(WHITELIST_FILE);\nlet file = File::open(&whitelist_path);\nif !overwrite && let Ok(mut file) = file {}\nexisting_data.extend(packed_chats);\nlet data = serde_json::to_string(&existing_data).unwrap();\nlet mut file = File::create(whitelist_path).unwrap();\nfile.write_all(data.as_bytes()).unwrap();\n}", + "body_hash": "c970cb3cf81b63df3b29bfc753c646cf4a057b3153d18189e8e83ff6bf287252" + } + } +} \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index d229f5c..7b56eef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -20,18 +20,18 @@ checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" [[package]] name = "accesskit" -version = "0.25.1" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932" +checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be" dependencies = [ "uuid", ] [[package]] name = "accesskit_atspi_common" -version = "0.21.0" +version = "0.21.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52c182f9c282ac9c5638d876d551d15e5f7d397ec263349a0c6a2b61595dd5e4" +checksum = "24f5baf62e34a4a6c30e3d697e4782f821a7337049c44c3b40576a27dfbb580d" dependencies = [ "accesskit", "accesskit_consumer", @@ -43,9 +43,9 @@ dependencies = [ [[package]] name = "accesskit_consumer" -version = "0.39.1" +version = "0.39.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344" +checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3" dependencies = [ "accesskit", "hashbrown 0.17.1", @@ -53,9 +53,9 @@ dependencies = [ [[package]] name = "accesskit_ios" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28e539d64b27fd4c14de8f78ada8f7c944c092f52f7e49fb63316507a57f6937" +checksum = "a5280724673bbfa8b30a838c013500b719392989be3b97c5a9964062c252c232" dependencies = [ "accesskit", "accesskit_consumer", @@ -67,9 +67,9 @@ dependencies = [ [[package]] name = "accesskit_macos" -version = "0.27.1" +version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4" +checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84" dependencies = [ "accesskit", "accesskit_consumer", @@ -81,9 +81,9 @@ dependencies = [ [[package]] name = "accesskit_unix" -version = "0.24.0" +version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "202f24df034a7476d07b7f74284de84f6d62aabd858dbe7ee9cad3b7ad6f8f9d" +checksum = "30d5192871228c54f1b0fb4a85cef000e11a3804f25d2165f14afa0daa67f3f6" dependencies = [ "accesskit", "accesskit_atspi_common", @@ -99,9 +99,9 @@ dependencies = [ [[package]] name = "accesskit_windows" -version = "0.35.1" +version = "0.35.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce63f35d6bdcf59f26b76b3379063f738e6412cef46999cc772d46aa3de35adb" +checksum = "498668b90da9995302a0055aaecad4756932333da2ddef6baee1c00844c430fc" dependencies = [ "accesskit", "accesskit_consumer", @@ -113,9 +113,9 @@ dependencies = [ [[package]] name = "accesskit_winit" -version = "0.34.1" +version = "0.34.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee96dd150375c05912d8a473f98c2fb155fb3234fac88292d396548a2460fa77" +checksum = "cd4ab4437b520ff03088fbe48676a11e7d44a929535e64b31432c1073e48dbcc" dependencies = [ "accesskit", "accesskit_ios", @@ -134,13 +134,13 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aes" -version = "0.8.4" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" dependencies = [ - "cfg-if", "cipher", - "cpufeatures 0.2.17", + "cpubits", + "cpufeatures", ] [[package]] @@ -153,7 +153,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "version_check", - "zerocopy", + "zerocopy 0.8.63", ] [[package]] @@ -279,9 +279,9 @@ dependencies = [ [[package]] name = "async-executor" -version = "1.14.0" +version = "1.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +checksum = "f426a31126c735126297bc5ea7a521263c9faff4f63ca415267ee625651c4f37" dependencies = [ "async-task", "concurrent-queue", @@ -304,16 +304,16 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] [[package]] name = "async-lock" -version = "3.4.2" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +checksum = "0876700b0d007ad25d5508865a4259c3af9af6d296bf663a0d586d0bc3369f6f" dependencies = [ "event-listener", "event-listener-strategy", @@ -335,7 +335,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -346,7 +346,7 @@ checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -361,7 +361,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -381,7 +381,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -435,9 +435,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.18.2" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "zeroize", @@ -445,9 +445,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.46.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -456,12 +456,41 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base64" version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bindgen" +version = "0.66.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "lazy_static", + "lazycell", + "log", + "peeking_take_while", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", + "which", +] + [[package]] name = "bit-set" version = "0.10.0" @@ -491,11 +520,11 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "block-buffer" -version = "0.10.4" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -552,9 +581,15 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -566,6 +601,9 @@ name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] [[package]] name = "calloop" @@ -589,7 +627,7 @@ checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" dependencies = [ "bitflags 2.13.2", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "tracing", ] @@ -612,21 +650,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "138efcf0940a02ebf0cc8d1eff41a1682a46b431630f4c52450d6265876021fa" dependencies = [ "calloop 0.14.5", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-client", ] [[package]] name = "cc" -version = "1.9.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" dependencies = [ "find-msvc-tools", "jobserver", "libc", - "shlex", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", ] [[package]] @@ -657,39 +704,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", - "cpufeatures 0.3.1", - "rand_core 0.10.1", + "cpufeatures", + "rand_core", ] [[package]] -name = "chrono" -version = "0.4.45" +name = "cipher" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", + "block-buffer", + "crypto-common", + "inout", ] [[package]] -name = "cipher" -version = "0.4.4" +name = "clang-sys" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" dependencies = [ - "crypto-common", - "inout", + "glob", + "libc", + "libloading", ] [[package]] name = "clipboard-win" -version = "5.4.1" +version = "5.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" dependencies = [ "error-code", ] @@ -703,6 +748,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "codespan-reporting" version = "0.13.1" @@ -742,6 +793,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "core-foundation" version = "0.9.4" @@ -799,13 +856,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" [[package]] -name = "cpufeatures" -version = "0.2.17" +name = "cpubits" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" [[package]] name = "cpufeatures" @@ -818,9 +872,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.5.2" +version = "1.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" dependencies = [ "cfg-if", ] @@ -856,14 +910,36 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-bigint" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" +dependencies = [ + "cpubits", + "ctutils", + "num-traits", + "rand_core", + "serdect", +] + [[package]] name = "crypto-common" -version = "0.1.7" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ - "generic-array", - "typenum", + "hybrid-array", +] + +[[package]] +name = "crypto-primes" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f" +dependencies = [ + "crypto-bigint", + "rand_core", ] [[package]] @@ -888,51 +964,39 @@ dependencies = [ ] [[package]] -name = "cursor-icon" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" - -[[package]] -name = "defmt" -version = "1.2.0" +name = "ctr" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" dependencies = [ - "bitflags 1.3.2", - "defmt-macros", + "cipher", ] [[package]] -name = "defmt-macros" -version = "1.2.0" +name = "ctutils" +version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" dependencies = [ - "defmt-parser", - "proc-macro2", - "quote", - "syn 3.0.9", + "cmov", ] [[package]] -name = "defmt-parser" -version = "1.1.0" +name = "cursor-icon" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" -dependencies = [ - "thiserror 2.0.21", -] +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" [[package]] name = "digest" -version = "0.10.7" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ "block-buffer", + "const-oid", "crypto-common", - "subtle", + "ctutils", ] [[package]] @@ -980,7 +1044,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1226,9 +1290,9 @@ dependencies = [ [[package]] name = "encoding_rs" -version = "0.8.42" +version = "0.8.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" dependencies = [ "cfg-if", "core_detect", @@ -1261,7 +1325,7 @@ checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1338,9 +1402,9 @@ checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "errno" -version = "0.3.14" +version = "0.3.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", "windows-sys 0.61.2", @@ -1416,15 +1480,15 @@ checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" [[package]] name = "fixedbitset" -version = "0.5.7" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +checksum = "5905ec755cc8386d7928353e4d356d2be3e89e81e5ca01fe630a1ca4d08dc175" [[package]] name = "flate2" -version = "1.1.10" +version = "1.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" dependencies = [ "crc32fast", "miniz_oxide 0.9.1", @@ -1498,7 +1562,7 @@ checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1522,6 +1586,21 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -1529,6 +1608,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -1537,6 +1617,17 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + [[package]] name = "futures-io" version = "0.3.34" @@ -1564,7 +1655,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -1585,30 +1676,24 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", + "futures-io", "futures-macro", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "slab", ] -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - [[package]] name = "gethostname" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -1647,7 +1732,7 @@ dependencies = [ "js-sys", "libc", "r-efi 6.0.0", - "rand_core 0.10.1", + "rand_core", "wasm-bindgen", ] @@ -1664,15 +1749,18 @@ dependencies = [ [[package]] name = "glass_pumpkin" -version = "1.9.1" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a36979d857bcca97269ce131d225ed43289c6613a86067831b34b3171765913" +checksum = "6ff9ef01d1ba41822349a2a9970e706dc6035637957cdddecf32482a8a90e86e" dependencies = [ + "crypto-bigint", + "crypto-primes", + "getrandom 0.4.3", "num-bigint", "num-integer", "num-traits", - "once_cell", - "rand_core 0.6.4", + "rand_core", + "thiserror 2.0.21", ] [[package]] @@ -1692,6 +1780,12 @@ dependencies = [ "vello_common", ] +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + [[package]] name = "glow" version = "0.17.0" @@ -1786,34 +1880,32 @@ dependencies = [ [[package]] name = "grammers-client" -version = "0.7.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85c97c2ce2ade23eb00a35d192929a678bd5b1650c7f36eea8a7f0ecd2c79c33" +checksum = "0d72e6a294d409c22c860d442bc78894507c0ad066733acc27c5d23fed8ef9bb" dependencies = [ - "chrono", "futures-util", "grammers-crypto", - "grammers-mtproto", "grammers-mtsender", "grammers-session", "grammers-tl-types", - "locate-locale", - "log", + "jiff", "md5", "mime_guess", - "os_info", "pin-project-lite", "tokio", + "tracing", ] [[package]] name = "grammers-crypto" -version = "0.7.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17c75ce8d715d407a5767a94b5fd7b210106ec5c29c7be8ff4dfdca58de4dcf6" +checksum = "92ac80ab9b047d77ab16b1b9247b1d15d50779064ba6a7417c03c64c936d5316" dependencies = [ "aes", - "getrandom 0.2.17", + "ctr", + "getrandom 0.4.3", "glass_pumpkin", "hmac", "num-bigint", @@ -1825,72 +1917,71 @@ dependencies = [ [[package]] name = "grammers-mtproto" -version = "0.7.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d057562ccd5ac7437683534634e469875db27827a7febd42cb6b775ffd01dff" +checksum = "fc95dd02ac37101d8121e5098706a9c9b342e855ca7d7b8b5daa91ec7b119649" dependencies = [ - "bytes", "crc32fast", "flate2", - "getrandom 0.2.17", + "getrandom 0.4.3", "grammers-crypto", "grammers-tl-types", - "log", "num-bigint", "sha1", + "tracing", ] [[package]] name = "grammers-mtsender" -version = "0.7.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49b077919dbbacab7644f8479f0c4456625714313334986b4f7c812691aac96a" +checksum = "9a6339a64b7b70ae4447ae4ae7b1b5a1e2e15649882bf26550df356e7a8bb1a4" dependencies = [ "bytes", - "futures-util", - "grammers-crypto", "grammers-mtproto", + "grammers-session", "grammers-tl-types", - "log", + "locate-locale", + "os_info", "tokio", + "tracing", ] [[package]] name = "grammers-session" -version = "0.7.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03d5fea440a79a78d0d68b57f062d737a0aed0decee813bf3c232252f3b3f7da" +checksum = "221a58eaf6bfb61ecd1cb8bc58c20d2bc7ec3749b968bc90d52bcf9a8547d4e6" dependencies = [ - "grammers-crypto", - "grammers-tl-gen", - "grammers-tl-parser", "grammers-tl-types", - "log", + "libsql", + "tokio", + "tracing", ] [[package]] name = "grammers-tl-gen" -version = "0.7.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c214cadfba8cd8ef9368bdf273f56f688537b0310ea42f91fc746f4fd59b70b9" +checksum = "b9d0672f6b59ba19c8946f934ddc005a9f44761e0a6e01867fcd7109e87c1614" dependencies = [ "grammers-tl-parser", ] [[package]] name = "grammers-tl-parser" -version = "1.2.2" +version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "646fc5eeb27461ffcc94fcf9fda3ffd9b402a20250447ae4a65c39c1a905e381" +checksum = "501ee4653d8328c5a3e8d1dd41825ed3bd9226a621b835ffacea8b1722ebe758" dependencies = [ "crc32fast", ] [[package]] name = "grammers-tl-types" -version = "0.7.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49566409a69e4ff3340c1b6f392e5754c89fa1ea43be4584ac8ee74c1eb0643a" +checksum = "eb4da570f8dbcea3e0d0a1746240045555bacc56b4d57d3a81204ee0e84736bd" dependencies = [ "grammers-tl-gen", "grammers-tl-parser", @@ -1933,7 +2024,7 @@ dependencies = [ "cfg-if", "crunchy", "num-traits", - "zerocopy", + "zerocopy 0.8.63", ] [[package]] @@ -1997,13 +2088,22 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "hmac" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" dependencies = [ "digest", ] +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "http" version = "1.5.0" @@ -2049,6 +2149,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "15cdd26707701c53297e2fa6afb323d55fbc1d0810c3aec078ae3ef0424c3c15" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -2111,35 +2220,11 @@ dependencies = [ "windows-registry", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" dependencies = [ "displaydoc", "potential_utf", @@ -2151,9 +2236,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", @@ -2164,9 +2249,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -2178,15 +2263,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" [[package]] name = "icu_properties" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" dependencies = [ "displaydoc", "icu_collections", @@ -2199,15 +2284,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.3.0" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" [[package]] name = "icu_provider" -version = "2.3.1" +version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", @@ -2265,11 +2350,11 @@ dependencies = [ [[package]] name = "inout" -version = "0.1.4" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" dependencies = [ - "generic-array", + "hybrid-array", ] [[package]] @@ -2319,17 +2404,16 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.18" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" [[package]] name = "jiff" -version = "0.2.38" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a" dependencies = [ - "defmt", "jiff-core", "jiff-static", "jiff-tzdb-platform", @@ -2344,19 +2428,18 @@ dependencies = [ [[package]] name = "jiff-core" -version = "0.1.1" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2" dependencies = [ - "defmt", "log", ] [[package]] name = "jiff-static" -version = "0.2.38" +version = "0.2.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a" dependencies = [ "jiff-core", "proc-macro2", @@ -2449,9 +2532,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" dependencies = [ "cfg-if", "futures-util", @@ -2487,6 +2570,18 @@ dependencies = [ "smallvec", ] +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + [[package]] name = "libc" version = "0.2.191" @@ -2521,6 +2616,47 @@ dependencies = [ "redox_syscall 0.9.5", ] +[[package]] +name = "libsql" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bca1704194048f0f0bbc8a8e05ba85c0c67628b03bd59346dd2fdd946a1588" +dependencies = [ + "async-trait", + "bitflags 2.13.2", + "bytes", + "futures", + "libsql-sys", + "parking_lot", + "thiserror 1.0.69", + "tracing", +] + +[[package]] +name = "libsql-ffi" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f232292810b6298d17466b59bf8077d075fb016d89c281ca9dc968ea4a3b9d03" +dependencies = [ + "bindgen", + "cc", + "cmake", + "glob", +] + +[[package]] +name = "libsql-sys" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4a7f2d76f49442c273a892a574a272b8b35f4bf0b1b25a475f2cc95885fe0f" +dependencies = [ + "bytes", + "libsql-ffi", + "once_cell", + "tracing", + "zerocopy 0.7.35", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -2571,9 +2707,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" [[package]] name = "lru-slab" @@ -2583,9 +2719,9 @@ checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" [[package]] name = "md5" -version = "0.7.0" +version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" +checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" [[package]] name = "memchr" @@ -2595,9 +2731,9 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" -version = "0.9.11" +version = "0.9.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" dependencies = [ "libc", ] @@ -2613,9 +2749,9 @@ dependencies = [ [[package]] name = "mime" -version = "0.3.17" +version = "0.3.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" [[package]] name = "mime_guess" @@ -2627,6 +2763,12 @@ dependencies = [ "unicase", ] +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2760,6 +2902,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + [[package]] name = "nom" version = "8.0.0" @@ -2781,13 +2933,13 @@ dependencies = [ [[package]] name = "num-bigint" -version = "0.4.8" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" dependencies = [ "num-integer", "num-traits", - "rand 0.8.8", + "rand_core", ] [[package]] @@ -3223,9 +3375,9 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "open" -version = "5.4.4" +version = "5.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc" +checksum = "8d8c8b8e725ad26404d6896eb2f064294a0a7b4f1d9120210d85544684c4ca95" dependencies = [ "is-wsl", "libc", @@ -3233,9 +3385,9 @@ dependencies = [ [[package]] name = "openssl-probe" -version = "0.2.1" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" [[package]] name = "option-ext" @@ -3255,9 +3407,9 @@ dependencies = [ [[package]] name = "ordered-float" -version = "5.5.0" +version = "5.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +checksum = "7f59006ce1e204c30956638535b74d317bca99477b9356dfaec54c37f6f600ab" dependencies = [ "num-traits", ] @@ -3343,14 +3495,20 @@ checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" [[package]] name = "pbkdf2" -version = "0.12.2" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" dependencies = [ "digest", "hmac", ] +[[package]] +name = "peeking_take_while" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" + [[package]] name = "peniko" version = "0.6.1" @@ -3506,7 +3664,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -3565,6 +3723,16 @@ dependencies = [ "log", ] +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -3640,7 +3808,7 @@ dependencies = [ "bytes", "getrandom 0.4.3", "lru-slab", - "rand 0.10.3", + "rand", "rand_pcg", "ring", "rustc-hash 2.1.3", @@ -3688,15 +3856,6 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" -[[package]] -name = "rand" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" -dependencies = [ - "rand_core 0.6.4", -] - [[package]] name = "rand" version = "0.10.3" @@ -3705,16 +3864,7 @@ checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ "chacha20", "getrandom 0.4.3", - "rand_core 0.10.1", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", + "rand_core", ] [[package]] @@ -3729,7 +3879,7 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" dependencies = [ - "rand_core 0.10.1", + "rand_core", ] [[package]] @@ -3915,9 +4065,9 @@ dependencies = [ [[package]] name = "roxmltree" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ "memchr", ] @@ -3958,9 +4108,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -3997,9 +4147,9 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.15.1" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ "web-time", "zeroize", @@ -4167,7 +4317,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4191,31 +4341,47 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", ] [[package]] name = "sha1" -version = "0.10.7" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" dependencies = [ "cfg-if", - "cpufeatures 0.2.17", + "cpufeatures", "digest", ] [[package]] name = "sha2" -version = "0.10.9" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", - "cpufeatures 0.2.17", + "cpufeatures", "digest", ] +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "shlex" version = "2.0.1" @@ -4287,9 +4453,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.16.3" +version = "1.16.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" [[package]] name = "smithay-client-toolkit" @@ -4329,7 +4495,7 @@ dependencies = [ "libc", "log", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "wayland-backend", "wayland-client", @@ -4437,9 +4603,9 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.9" +version = "3.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" dependencies = [ "proc-macro2", "quote", @@ -4463,7 +4629,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4500,7 +4666,6 @@ dependencies = [ name = "talon-gui" version = "2.0.0" dependencies = [ - "chrono", "csv", "dirs", "eframe", @@ -4538,7 +4703,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -4588,7 +4753,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -4632,9 +4797,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" dependencies = [ "displaydoc", "zerovec", @@ -4648,18 +4813,30 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "tokio" -version = "1.54.0" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ "bytes", "libc", "mio", "pin-project-lite", "socket2", + "tokio-macros", "windows-sys 0.61.2", ] +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "tokio-rustls" version = "0.26.6" @@ -4686,18 +4863,18 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" dependencies = [ "serde_core", ] [[package]] name = "toml_edit" -version = "0.25.17+spec-1.1.0" +version = "0.25.19+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" dependencies = [ "indexmap", "toml_datetime", @@ -4798,7 +4975,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" dependencies = [ "memchr", - "nom", + "nom 8.0.0", "petgraph", ] @@ -4860,15 +5037,15 @@ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-properties" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" [[package]] name = "unicode-script" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" +checksum = "aa04c955db05429d464c74d495c1ee677e1866e783a4c3747f9c0cef7756cabf" [[package]] name = "unicode-segmentation" @@ -4878,9 +5055,9 @@ checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" [[package]] name = "unicode-width" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" [[package]] name = "untrusted" @@ -4902,15 +5079,24 @@ dependencies = [ [[package]] name = "utf8_iter" -version = "1.0.4" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" [[package]] name = "uuid" -version = "1.28.0" +version = "1.29.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" dependencies = [ "js-sys", "serde_core", @@ -4988,12 +5174,11 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" dependencies = [ "cfg-if", - "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared", @@ -5001,9 +5186,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.79" +version = "0.4.80" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" dependencies = [ "js-sys", "tokio", @@ -5012,9 +5197,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -5022,22 +5207,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" -version = "0.2.129" +version = "0.2.130" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" dependencies = [ "unicode-ident", ] @@ -5050,7 +5235,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -5063,7 +5248,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -5085,7 +5270,7 @@ version = "0.31.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "wayland-client", "xcursor", ] @@ -5179,9 +5364,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.106" +version = "0.3.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" dependencies = [ "js-sys", "wasm-bindgen", @@ -5199,9 +5384,9 @@ dependencies = [ [[package]] name = "webbrowser" -version = "1.2.4" +version = "1.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62c35be770821a214dbc362fc26908c853e776c0004294d0b10b8a6bad582f94" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" dependencies = [ "jni", "log", @@ -5215,9 +5400,9 @@ dependencies = [ [[package]] name = "webpki-root-certs" -version = "1.0.10" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ec80e73fd8baf57bf0d9615554c75348bda990d6d5bbeab964dd068319fecb" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] @@ -5411,6 +5596,18 @@ dependencies = [ "web-sys", ] +[[package]] +name = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix 0.38.44", +] + [[package]] name = "winapi" version = "0.3.9" @@ -5708,9 +5905,9 @@ dependencies = [ [[package]] name = "winnow" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" dependencies = [ "memchr", ] @@ -5723,14 +5920,14 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" [[package]] name = "wl-clipboard-rs" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1" +checksum = "959c7ac3b8afde864f7a7448ac16f29b2b83350b7eccbf77fb781c3999aa6848" dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -5767,7 +5964,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -5821,9 +6018,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.3" +version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -5838,7 +6035,7 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -5864,7 +6061,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", @@ -5910,7 +6107,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "zbus_names", "zvariant", "zvariant_utils", @@ -5941,20 +6138,41 @@ dependencies = [ [[package]] name = "zcheapstr" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920" dependencies = [ "serde", ] +[[package]] +name = "zerocopy" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b9b4fd18abc82b8136838da5d50bae7bdea537c574d8dc1a34ed098d6c166f0" +dependencies = [ + "byteorder", + "zerocopy-derive 0.7.35", +] + [[package]] name = "zerocopy" version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ - "zerocopy-derive", + "zerocopy-derive 0.8.63", +] + +[[package]] +name = "zerocopy-derive" +version = "0.7.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -5985,7 +6203,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "synstructure", ] @@ -6008,9 +6226,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.8" +version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" dependencies = [ "yoke", "zerofrom", @@ -6019,13 +6237,13 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.6" +version = "0.11.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", ] [[package]] @@ -6079,7 +6297,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.9", + "syn 3.0.10", "zvariant_utils", ] @@ -6092,6 +6310,6 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn 3.0.9", + "syn 3.0.10", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index 3eaefd3..987b740 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,16 +2,13 @@ name = "talon-gui" version = "2.0.0" edition = "2024" -description = """ -On-demand Telegram chat analytic generator -""" +description = "On-demand Telegram chat analytic generator" readme = "README.md" homepage = "https://github.com/TheRustyPickle/Talon" repository = "https://github.com/TheRustyPickle/Talon" license = "MIT" -keywords = ["analytics", "data", "egui", "gui", "telegram"] -categories = ["gui"] -exclude = ["/fonts"] +keywords = ["analytics", "egui", "grammers", "statistics", "telegram"] +categories = ["gui", "visualization"] [[bin]] name = "talon" @@ -20,7 +17,6 @@ path = "src/main.rs" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -chrono = { version = "0.4.45", features = ["serde"] } csv = "1.4.0" dirs = "7.0.0" eframe = "0.37.0" @@ -30,17 +26,17 @@ egui_extras = { version = "0.37.0", default-features = false, features = [ egui_plot = "0.38.0" egui-selectable-table = { version = "0.9.0", features = ["fuzzy-matching", "rayon"] } egui-theme-lerp = "0.8.0" -grammers-client = "=0.7.0" -grammers-crypto = "=0.7.0" -grammers-mtproto = "=0.7.0" -grammers-mtsender = "=0.7.0" -grammers-session = "=0.7.0" -grammers-tl-gen = "=0.7.0" -grammers-tl-types = "=0.7.0" -jiff = "0.2.38" -log = "0.4.34" +grammers-client = "=0.12.0" +grammers-crypto = "=0.12.0" +grammers-mtproto = "=0.12.0" +grammers-mtsender = "=0.12.0" +grammers-session = "=0.12.0" +grammers-tl-gen = "=0.12.0" +grammers-tl-types = "=0.12.0" +jiff = { version = "0.2.43", features = ["serde"] } +log = "0.4.35" nucleo-matcher = "0.3.1" -open = "5.4.4" +open = "5.4.5" pretty_env_logger = "0.5.0" reqwest = { version = "0.13.5", features = ["json"] } semver = "1.0.28" @@ -48,7 +44,7 @@ serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" strum = "0.28.0" strum_macros = "0.28.0" -tokio = { version = "1.53.3", features = ["rt-multi-thread"] } +tokio = { version = "1.54.1", features = ["rt-multi-thread"] } # The profile that 'cargo dist' will build with [profile.dist] diff --git a/README.md b/README.md index 7d8a5e5..74c828b 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,26 @@ Talon is a tool to generate on-demand data insights from public Telegram chats. Powered by Rust, grammers, and egui, it offers a straightforward interface that leverages the Telegram account API. -![screenshot](https://github.com/user-attachments/assets/6f8cad44-6de3-4f5b-a947-768eca531d74) +

+ Users table with per-user stats +

+ +
+More screenshots + +**Scan** + +Scan tab + +**Charts** + +Charts tab + +**Accounts** + +Accounts tab + +
## Features @@ -22,10 +41,14 @@ Talon is a tool to generate on-demand data insights from public Telegram chats. - **Blacklisting:** Exclude specific users from data analysis to prevent their data from appearing in the results. - **Multi-Session Capability:** Utilize multiple sessions to dramatically increase checking speed, tested with up to 12 sessions and 300k messages. - **Multi-Chat Capability:** Analyze multiple chats simultaneously and view data from each chat separately. +- **Scan Range:** Paste a message link to start from, and optionally one to end at, to count only a specific part of a chat. +- **Search:** Filter the users table and the whitelist/blacklist by name, username or user ID. +- **Customizable Charts:** Pick which users appear on a chart and toggle the total and whitelisted series with a click. +- **CSV Export:** Export the users table to a CSV file. ## Important Note -Talon uses the [grammers library](https://github.com/lonami/grammers) for Telegram operations. Please be aware that grammers is currently under development and may not be stable or audited for security. +Talon uses the [grammers library](https://codeberg.org/Lonami/grammers) for Telegram operations. Please be aware that grammers is currently under development and may not be stable or audited for security. ## Installation diff --git a/dist-workspace.toml b/dist-workspace.toml index c25a0a9..03bd994 100644 --- a/dist-workspace.toml +++ b/dist-workspace.toml @@ -4,7 +4,7 @@ members = ["cargo:."] # Config for 'dist' [dist] # The preferred dist version to use in CI (Cargo.toml SemVer syntax) -cargo-dist-version = "0.32.0" +cargo-dist-version = "0.34.0" # CI backends to support ci = "github" # The installers to generate for each app diff --git a/fonts/GentiumBookPlus-Regular.ttf b/fonts/GentiumBookPlus-Regular.ttf deleted file mode 100644 index 00ad30a..0000000 Binary files a/fonts/GentiumBookPlus-Regular.ttf and /dev/null differ diff --git a/fonts/NotoSansCJK-Regular.ttc b/fonts/NotoSansCJK-Regular.ttc deleted file mode 100644 index a2033d0..0000000 Binary files a/fonts/NotoSansCJK-Regular.ttc and /dev/null differ diff --git a/screenshots/accounts.png b/screenshots/accounts.png new file mode 100644 index 0000000..eed2644 Binary files /dev/null and b/screenshots/accounts.png differ diff --git a/screenshots/charts.png b/screenshots/charts.png new file mode 100644 index 0000000..9991274 Binary files /dev/null and b/screenshots/charts.png differ diff --git a/screenshots/scan.png b/screenshots/scan.png new file mode 100644 index 0000000..24207ba Binary files /dev/null and b/screenshots/scan.png differ diff --git a/screenshots/users.png b/screenshots/users.png new file mode 100644 index 0000000..b66789f Binary files /dev/null and b/screenshots/users.png differ diff --git a/src/main.rs b/src/main.rs index bf3bbb0..d58d087 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,8 @@ -mod tg_handler; -mod ui_components; +mod telegram; +mod ui; mod utils; -use crate::ui_components::MainWindow; +use crate::ui::MainWindow; use dirs::data_local_dir; use eframe::{NativeOptions, egui}; use egui::{ViewportBuilder, vec2}; @@ -38,15 +38,18 @@ fn main() { set_current_dir(target_location).unwrap(); info!("Starting app"); + let viewport = ViewportBuilder::default() .with_title("Talon") .with_inner_size(vec2(600.0, 450.0)) .with_resizable(true) .with_maximize_button(false); + let native_options = NativeOptions { viewport, ..Default::default() }; + eframe::run_native( "Talon", native_options, @@ -54,7 +57,7 @@ fn main() { ) .unwrap(); } else { - println!("Failed to get local data directory. Exiting"); + info!("Failed to get local data directory. Exiting"); std::process::exit(1); } } diff --git a/src/telegram/backend.rs b/src/telegram/backend.rs new file mode 100644 index 0000000..7c6fda1 --- /dev/null +++ b/src/telegram/backend.rs @@ -0,0 +1,251 @@ +use eframe::egui::Context; +use grammers_client::client::{LoginToken, PasswordToken}; +use log::error; +use std::collections::BTreeMap; +use std::future::Future; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, channel}; +use tokio::runtime::Runtime; + +use crate::telegram::events::{Packet, StateUpdate}; +use crate::telegram::{ + Command, Event, EventSink, ProcessError, TGClient, check_scan_sessions, connect_to_session, + refresh_sessions, send_login_code, +}; +use crate::utils::get_runtime; + +/// A login that is waiting for the user to finish it +struct PendingLogin { + client: TGClient, + code_token: Arc, + password_token: Option, +} + +/// Everything on the Telegram side that the GUI talks to. +pub struct Backend { + runtime: Runtime, + sink: EventSink, + receiver: Receiver, + clients: BTreeMap, + pending: Option, + cancel_scan: Arc, +} + +impl Backend { + pub fn new(context: Context) -> Self { + let (sender, receiver) = channel(); + + Self { + runtime: get_runtime(), + sink: EventSink::new(sender, context), + receiver, + clients: BTreeMap::new(), + pending: None, + cancel_scan: Arc::new(AtomicBool::new(false)), + } + } + + /// Next event for the GUI, if any. State changes that come before it are applied first + pub fn poll(&mut self) -> Option { + loop { + match self.receiver.try_recv().ok()? { + Packet::Event(event) => return Some(event), + Packet::State(update) => self.apply(update), + } + } + } + + fn apply(&mut self, update: StateUpdate) { + match update { + StateUpdate::ClientsRestored(clients) => { + for client in clients { + self.clients.insert(client.name(), client); + } + } + StateUpdate::LoginCodeSent { client, token } => { + self.pending = Some(PendingLogin { + client, + code_token: Arc::new(token), + password_token: None, + }); + } + StateUpdate::PasswordRequired(token) | StateUpdate::PasswordRejected(token) => { + if let Some(pending) = &mut self.pending { + pending.password_token = Some(token); + } + } + StateUpdate::SessionsDropped(names) => { + for name in names { + self.clients.remove(&name); + } + } + StateUpdate::LoggedIn(client) => { + self.pending = None; + self.clients.insert(client.name(), client); + } + } + } + + /// Names of the connected sessions in alphabetical order + pub fn session_names(&self) -> Vec { + self.clients.keys().cloned().collect() + } + + pub fn session_count(&self) -> usize { + self.clients.len() + } + + pub fn has_session(&self, name: &str) -> bool { + self.clients.contains_key(name) + } + + /// Forget a login that was started but not finished + pub fn cancel_login(&mut self) { + self.pending = None; + } + + /// Ask the running count to stop at the next message + pub fn cancel_scan(&self) { + self.cancel_scan.store(true, Ordering::Release); + } + + /// Must be called before a fresh scan, otherwise it would stop right away after a cancel + pub fn reset_cancel(&self) { + self.cancel_scan.store(false, Ordering::Relaxed); + } + + /// Run any async job that does not report back through events + pub fn spawn(&self, task: impl Future + Send + 'static) { + self.runtime.spawn(task); + } + + /// Runs a job and reports its error to the GUI + fn run(&self, task: impl Future> + Send + 'static) { + let sink = self.sink.clone(); + + self.runtime.spawn(async move { + if let Err(err) = task.await { + error!("Error acquired while handling a command: {err:?}"); + sink.event(err); + } + }); + } + + /// Log out of the sessions that were created as temporary and wait for it to finish + pub fn logout_temporary_sessions(&self) { + let handles: Vec<_> = self + .clients + .values() + .filter(|client| client.is_temporary()) + .cloned() + .map(|client| self.runtime.spawn(async move { client.logout().await })) + .collect(); + + for handle in handles { + let _ = self.runtime.block_on(handle); + } + } + + pub fn send(&mut self, command: Command) { + match command { + Command::ConnectSavedSessions(names) => { + self.run(connect_to_session(self.sink.clone(), names)); + } + Command::RefreshSessions { new_files } => { + let clients: Vec = self.clients.values().cloned().collect(); + self.run(refresh_sessions(self.sink.clone(), clients, new_files)); + } + Command::RequestLoginCode { + session, + phone, + temporary, + } => { + self.run(send_login_code( + self.sink.clone(), + session, + phone, + temporary, + )); + } + Command::SubmitLoginCode { code } => { + let Some(pending) = &self.pending else { + return self.reject("no login is waiting for a code"); + }; + + let client = pending.client.clone(); + let token = pending.code_token.clone(); + self.run(async move { client.sign_in_code(token, code).await }); + } + Command::SubmitPassword { password } => { + let Some(pending) = &mut self.pending else { + return self.reject("no login is waiting for a password"); + }; + + let Some(token) = pending.password_token.take() else { + return self.reject("the password token is already in use"); + }; + + let client = pending.client.clone(); + self.run(async move { client.sign_in_password(token, password).await }); + } + Command::CheckChat { + session, + chat, + start, + end, + } => { + let clients: Vec = self.clients.values().cloned().collect(); + self.run(check_scan_sessions(clients, session, chat, start, end)); + } + Command::StartCount { + session, + chat, + start, + end, + multi_session, + } => { + let cancel = self.cancel_scan.clone(); + self.with_client(&session, |client| async move { + client + .start_count(chat, start, end, multi_session, cancel) + .await + }); + } + Command::LoadList { + kind, + session, + peers, + } => { + self.with_client(&session, |client| async move { + client.load_list_users(kind, peers).await + }); + } + Command::AddListUser { + kind, + session, + username, + } => { + self.with_client(&session, |client| async move { + client.add_list_user(kind, username).await + }); + } + } + } + + fn with_client(&self, session: &str, task: F) + where + F: FnOnce(TGClient) -> Fut, + Fut: Future> + Send + 'static, + { + match self.clients.get(session) { + Some(client) => self.run(task(client.clone())), + None => self.reject(&format!("session {session} is not connected")), + } + } + + fn reject(&self, reason: &str) { + error!("Command rejected: {reason}"); + self.sink.event(ProcessError::UnknownSession); + } +} diff --git a/src/telegram/client.rs b/src/telegram/client.rs new file mode 100644 index 0000000..147ff3a --- /dev/null +++ b/src/telegram/client.rs @@ -0,0 +1,91 @@ +use grammers_client::{Client, peer::Peer}; +use log::{error, info}; + +use crate::telegram::{AccountEvent, Event, EventSink, ProcessError}; + +/// A connected Telegram account. Created and kept by the [`Backend`] +#[derive(Clone)] +pub struct TGClient { + client: Client, + name: String, + sink: EventSink, + is_temporary: bool, +} + +impl TGClient { + pub fn new(client: Client, name: String, sink: EventSink, is_temporary: bool) -> Self { + TGClient { + client, + name, + sink, + is_temporary, + } + } + + pub fn name(&self) -> String { + self.name.clone() + } + + /// Tell the GUI something happened + pub fn send(&self, event: impl Into) { + self.sink.event(event); + } + + pub fn sink(&self) -> &EventSink { + &self.sink + } + + pub fn client(&self) -> &Client { + &self.client + } + + pub fn is_temporary(&self) -> bool { + self.is_temporary + } + + /// Verifies if the current client is authorized for usage + pub async fn check_authorization(&self) -> Result { + let authorized: bool = self + .client() + .is_authorized() + .await + .map_err(ProcessError::UnknownError)?; + + info!("Client authorization status: {authorized}"); + + if !authorized { + self.send(AccountEvent::Unauthorized(self.name())); + return Ok(false); + } + + Ok(true) + } + + /// Tries to resolve a username to get a Telegram chat account + pub async fn check_username(&self, chat_name: &str) -> Result { + let tg_chat = self.client().resolve_username(chat_name).await; + + let Ok(tg_chat) = tg_chat else { + error!("Failed to resolve username"); + return Err(ProcessError::InvalidChat(chat_name.to_owned())); + }; + + let Some(tg_chat) = tg_chat else { + error!("Found None value for target chat. Stopping processing"); + return Err(ProcessError::InvalidChat(chat_name.to_owned())); + }; + + let name = tg_chat.name().unwrap_or("No name"); + + info!("Target chat {} exist", name); + + Ok(tg_chat) + } + + /// Logs out of the client + pub async fn logout(&self) -> Result<(), ProcessError> { + let _ = self.client().sign_out().await; + info!("Logged out of client {}", self.name()); + Ok(()) + } +} diff --git a/src/telegram/commands.rs b/src/telegram/commands.rs new file mode 100644 index 0000000..f4d801d --- /dev/null +++ b/src/telegram/commands.rs @@ -0,0 +1,48 @@ +use grammers_session::types::PeerRef; + +use crate::ui::state::ListKind; + +/// Everything the GUI can ask the Telegram side to do. Sent through [`Backend::send`] +pub enum Command { + /// Connect to the saved session files and keep the ones that are still logged in + ConnectSavedSessions(Vec), + /// Drop sessions that got logged out and connect the given saved sessions + RefreshSessions { new_files: Vec }, + RequestLoginCode { + session: String, + phone: String, + temporary: bool, + }, + /// Finish the login that is waiting for a code + SubmitLoginCode { code: String }, + /// Finish the login that is waiting for the two-step verification password + SubmitPassword { password: String }, + /// Check that the chat exists and find the range to count + /// Verify every session still works, drop the ones that do not, then check the chat + /// with `session` (or another working one if it was dropped) + CheckChat { + session: String, + chat: String, + start: Option, + end: Option, + }, + StartCount { + session: String, + chat: String, + start: Option, + end: Option, + multi_session: bool, + }, + /// Resolve the saved users of a list + LoadList { + kind: ListKind, + session: String, + peers: Vec, + }, + /// Look up a username and add it to a list + AddListUser { + kind: ListKind, + session: String, + username: String, + }, +} diff --git a/src/telegram/events.rs b/src/telegram/events.rs new file mode 100644 index 0000000..f11cd88 --- /dev/null +++ b/src/telegram/events.rs @@ -0,0 +1,141 @@ +use eframe::egui::Context; +use grammers_client::InvocationError; +use grammers_client::client::{LoginToken, PasswordToken}; +use std::sync::mpsc::Sender; + +use crate::telegram::{TGClient, TGCountData}; +use crate::ui::state::{ListKind, UnpackedUser}; + +/// Everything the Telegram side can tell the GUI, grouped by topic +pub enum Event { + Account(AccountEvent), + Scan(ScanEvent), + Users(UsersEvent), + Failed(ProcessError), +} + +pub enum AccountEvent { + SessionsRestored { + connected: Vec, + failed: Vec, + }, + LoginCodeSent, + PasswordRequired, + LoggedIn(String), + Unauthorized(String), + /// Sessions that are no longer logged in and were removed + SessionsDropped(Vec), + /// A refresh finished without any new session to connect + SessionsRefreshed { + working: usize, + }, +} + +pub enum ScanEvent { + /// The chat exists, this is the message range to count + ChatChecked { + chat: String, + start: i32, + end: i32, + /// The sessions that passed the check and can share the work + sessions: Vec, + }, + Message(Box), + Finished { + end_at: i32, + last_number: i32, + }, + FloodWait, +} + +pub enum UsersEvent { + ListLoaded { + kind: ListKind, + users: Vec, + failed: i32, + }, + ListAdded { + kind: ListKind, + user: Box, + }, +} + +#[derive(Debug)] +pub enum ProcessError { + FileCreationError, + InvalidTGCode, + InvalidPassword, + NotSignedUp, + InvalidPhoneOrAPI(InvocationError), + InvalidAPIKeys, + InvalidChat(String), + /// Every session was logged out or unreachable + NoUsableSession, + FailedLatestMessage, + UnknownSession, + UnknownError(InvocationError), +} + +impl From for Event { + fn from(event: AccountEvent) -> Self { + Event::Account(event) + } +} + +impl From for Event { + fn from(event: ScanEvent) -> Self { + Event::Scan(event) + } +} + +impl From for Event { + fn from(event: UsersEvent) -> Self { + Event::Users(event) + } +} + +impl From for Event { + fn from(error: ProcessError) -> Self { + Event::Failed(error) + } +} + +pub(super) enum StateUpdate { + ClientsRestored(Vec), + LoginCodeSent { client: TGClient, token: LoginToken }, + PasswordRequired(PasswordToken), + PasswordRejected(PasswordToken), + LoggedIn(TGClient), + SessionsDropped(Vec), +} + +pub(super) enum Packet { + Event(Event), + State(StateUpdate), +} + +/// The only way for async code to reach the GUI. Wakes the GUI up after every message +#[derive(Clone)] +pub struct EventSink { + sender: Sender, + context: Context, +} + +impl EventSink { + pub(super) fn new(sender: Sender, context: Context) -> Self { + Self { sender, context } + } + + pub fn event(&self, event: impl Into) { + self.push(Packet::Event(event.into())); + } + + pub(super) fn state(&self, update: StateUpdate) { + self.push(Packet::State(update)); + } + + fn push(&self, packet: Packet) { + let _ = self.sender.send(packet); + self.context.request_repaint(); + } +} diff --git a/src/telegram/mod.rs b/src/telegram/mod.rs new file mode 100644 index 0000000..7fc3292 --- /dev/null +++ b/src/telegram/mod.rs @@ -0,0 +1,14 @@ +mod backend; +mod client; +mod commands; +mod events; +mod scan; +mod sessions; +mod users; + +pub use backend::*; +pub use client::*; +pub use commands::*; +pub use events::*; +pub use scan::*; +pub use sessions::*; diff --git a/src/tg_handler/counter.rs b/src/telegram/scan.rs similarity index 65% rename from src/tg_handler/counter.rs rename to src/telegram/scan.rs index 7f6e2fa..8830f1d 100644 --- a/src/tg_handler/counter.rs +++ b/src/telegram/scan.rs @@ -1,15 +1,17 @@ -use grammers_client::types::Message; +use grammers_client::message::Message; +use grammers_session::types::PeerRef; use log::info; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::{self, sleep}; use std::time::{Duration, Instant}; -use crate::tg_handler::{ProcessError, ProcessResult, TGClient}; +use crate::telegram::{ProcessError, ScanEvent, TGClient, verify_sessions}; pub struct TGCountData { name: String, message: Message, + sender_ref: Option, start_at: i32, end_at: i32, multi_session: bool, @@ -20,6 +22,7 @@ impl TGCountData { pub fn new( name: String, message: Message, + sender_ref: Option, start_at: i32, end_at: i32, last_number: i32, @@ -28,6 +31,7 @@ impl TGCountData { TGCountData { name, message, + sender_ref, start_at, end_at, multi_session, @@ -38,10 +42,15 @@ impl TGCountData { pub fn name(&self) -> String { self.name.clone() } + pub fn message(&self) -> &Message { &self.message } + pub fn sender_ref(&self) -> Option { + self.sender_ref + } + pub fn start_at(&self) -> i32 { self.start_at } @@ -73,17 +82,12 @@ impl TGClient { return Ok(()); } - let tg_chat = self.check_username(&start_chat).await; - - let tg_chat = match tg_chat { - Ok(chat) => chat, - Err(e) => { - self.send(e); - return Ok(()); - } - }; + let tg_chat = self.check_username(&start_chat).await?; - info!("{} exists. Starting iterating messages", tg_chat.name()); + info!( + "{} exists. Starting iterating messages", + tg_chat.name().unwrap_or("No Name") + ); let end_at = end_num.unwrap_or(1); let mut start_at = start_num.unwrap_or(-1); @@ -93,8 +97,7 @@ impl TGClient { let last_sent = Arc::new(Mutex::new(Some(Instant::now()))); let last_sent_clone = last_sent.clone(); - let sender = self.sender(); - let context = self.context(); + let sink = self.sink().clone(); // Every 500 ms, check when the last communication was made with the GUI. // If over 500, let the GUI side know that a flood wait was triggered @@ -107,8 +110,7 @@ impl TGClient { if let Some(last_sent) = *last_sent { let time_passed = last_sent.elapsed().as_millis(); if time_passed > 500 && time_passed < 1050 { - sender.send(ProcessResult::FloodWait).unwrap(); - context.request_repaint(); + sink.event(ScanEvent::FloodWait); } // stop this thread if no activity for over 60 seconds @@ -122,7 +124,18 @@ impl TGClient { }); let mut last_number = -1; - let mut iter_message = self.client().iter_messages(tg_chat); + + let peer_ref = tg_chat.to_ref().await; + + let Ok(peer_ref) = peer_ref else { + return Err(ProcessError::FailedLatestMessage); + }; + + let Some(peer_ref) = peer_ref else { + return Err(ProcessError::FailedLatestMessage); + }; + + let mut iter_message = self.client().iter_messages(peer_ref); // Add 1 to offset because the latest message would start from the offset point - 1 message // Add 1 to last_number if the starting message is 100 but does not exist and starts from 99, we want to count that missing message @@ -149,15 +162,23 @@ impl TGClient { } if message_num <= start_at { + // Only possible to get a reference if the sender is usable or cached in the session + let sender_ref = match message.sender() { + Some(sender) => sender.to_ref().await.ok().flatten(), + None => None, + }; + let count_data = TGCountData::new( self.name(), message, + sender_ref, start_at, end_at, last_number, multi_session, ); - self.send(ProcessResult::CountingMessage(Box::new(count_data))); + + self.send(ScanEvent::Message(Box::new(count_data))); last_number = message_num; } @@ -177,7 +198,11 @@ impl TGClient { let mut last_sent_lock = last_sent.lock().unwrap(); *last_sent_lock = None; - self.send(ProcessResult::CountingEnd((end_at, last_number))); + self.send(ScanEvent::Finished { + end_at, + last_number, + }); + Ok(()) } @@ -186,27 +211,30 @@ impl TGClient { start_chat: String, start_point: Option, end_point: Option, + sessions: Vec, ) -> Result<(), ProcessError> { if !self.check_authorization().await? { return Ok(()); } - let tg_chat = self.check_username(&start_chat).await; - - let tg_chat = match tg_chat { - Ok(chat) => chat, - Err(e) => { - self.send(e); - return Ok(()); - } - }; + let tg_chat = self.check_username(&start_chat).await?; let end_point = end_point.unwrap_or(1); let start_point = if let Some(num) = start_point { num } else { - let mut iter_message = self.client().iter_messages(tg_chat).limit(1); + let peer_ref = tg_chat.to_ref().await; + + let Ok(peer_ref) = peer_ref else { + return Err(ProcessError::FailedLatestMessage); + }; + + let Some(peer_ref) = peer_ref else { + return Err(ProcessError::FailedLatestMessage); + }; + + let mut iter_message = self.client().iter_messages(peer_ref).limit(1); if let Some(message) = iter_message .next() @@ -219,11 +247,37 @@ impl TGClient { } }; - self.send(ProcessResult::ChatExists( - start_chat, - start_point, - end_point, - )); + self.send(ScanEvent::ChatChecked { + chat: start_chat, + start: start_point, + end: end_point, + sessions, + }); + Ok(()) } } + +/// Checks that every session is still logged in before work is shared between them, then +/// checks the chat with the preferred session, or the first working one if that was dropped +pub async fn check_scan_sessions( + clients: Vec, + preferred: String, + chat: String, + start: Option, + end: Option, +) -> Result<(), ProcessError> { + let usable = verify_sessions(clients).await; + + let Some(checker) = usable + .iter() + .find(|client| client.name() == preferred) + .or(usable.first()) + .cloned() + else { + return Err(ProcessError::NoUsableSession); + }; + + let names = usable.iter().map(TGClient::name).collect(); + checker.check_chat_status(chat, start, end, names).await +} diff --git a/src/telegram/sessions/mod.rs b/src/telegram/sessions/mod.rs new file mode 100644 index 0000000..093ebc8 --- /dev/null +++ b/src/telegram/sessions/mod.rs @@ -0,0 +1,7 @@ +mod new; +mod restore; +mod verify; + +pub use new::*; +pub use restore::*; +pub use verify::*; diff --git a/src/telegram/sessions/new.rs b/src/telegram/sessions/new.rs new file mode 100644 index 0000000..4a8c806 --- /dev/null +++ b/src/telegram/sessions/new.rs @@ -0,0 +1,135 @@ +use grammers_client::client::{LoginToken, PasswordToken}; +use grammers_client::{Client, SignInError}; +use grammers_mtsender::SenderPool; +use grammers_session::storages::{MemorySession, SqliteSession}; +use log::{error, info}; +use std::fs; +use std::sync::Arc; + +use crate::telegram::events::StateUpdate; +use crate::telegram::{AccountEvent, EventSink, ProcessError, TGClient}; +use crate::utils::get_api_keys; + +/// Tries to send Telegram login code to the given phone number +pub async fn send_login_code( + sink: EventSink, + session_name: String, + phone_number: String, + is_temporary: bool, +) -> Result<(), ProcessError> { + let Some(api_data) = get_api_keys() else { + error!("No API keys found"); + return Err(ProcessError::InvalidAPIKeys); + }; + + let Ok(api_id) = api_data.api_id.parse() else { + error!("Failed to parse API ID. Given API ID: {}", api_data.api_id); + return Err(ProcessError::InvalidAPIKeys); + }; + let api_hash = api_data.api_hash; + + let pool = if is_temporary { + let session = Arc::new(MemorySession::default()); + SenderPool::new(Arc::clone(&session), api_id) + } else { + let target_path = format!("{session_name}.sqlite"); + + if fs::metadata(&target_path).is_ok() { + info!("{target_path} exists. Removing old sqlite file"); + fs::remove_file(&target_path).expect("Failed to remove old sqlite file"); + } + + let session = SqliteSession::open(target_path).await; + + if let Err(e) = session { + error!("Failed to create/open session file: {e}"); + return Err(ProcessError::FileCreationError); + } + + let session = Arc::new(session.unwrap()); + + SenderPool::new(Arc::clone(&session), api_id) + }; + + let SenderPool { runner, handle, .. } = pool; + tokio::spawn(runner.run()); + + let client = Client::new(handle); + + let code_token = client + .request_login_code(&phone_number, &api_hash) + .await + .map_err(ProcessError::InvalidPhoneOrAPI)?; + + let new_client = TGClient::new(client, session_name, sink.clone(), is_temporary); + + sink.state(StateUpdate::LoginCodeSent { + client: new_client, + token: code_token, + }); + + sink.event(AccountEvent::LoginCodeSent); + + Ok(()) +} + +impl TGClient { + /// Tries to sign in to a Telegram account with the given Telegram login code + pub async fn sign_in_code( + &self, + token: Arc, + code: String, + ) -> Result<(), ProcessError> { + let result = self.client().sign_in(&token, &code).await; + + match result { + Ok(_) => { + self.finish_login(); + } + Err(err) => match err { + SignInError::InvalidCode => self.send(ProcessError::InvalidTGCode), + SignInError::PasswordRequired(token) => { + self.sink().state(StateUpdate::PasswordRequired(token)); + self.send(AccountEvent::PasswordRequired); + } + SignInError::SignUpRequired => self.send(ProcessError::NotSignedUp), + SignInError::InvalidPassword(_) => unreachable!(), + SignInError::Other(e) => self.send(ProcessError::UnknownError(e)), + }, + } + Ok(()) + } + + /// Tries to sign in to a Telegram account with the given login password. + /// May continue to fail if the first time password was not correct + pub async fn sign_in_password( + &self, + token: PasswordToken, + password: String, + ) -> Result<(), ProcessError> { + let result = self.client().check_password(token, password).await; + + match result { + Ok(_) => { + self.finish_login(); + } + Err(err) => match err { + SignInError::InvalidCode + | SignInError::PasswordRequired(_) + | SignInError::SignUpRequired => unreachable!(), + SignInError::InvalidPassword(new_token) => { + self.sink().state(StateUpdate::PasswordRejected(new_token)); + self.send(ProcessError::InvalidPassword); + } + SignInError::Other(e) => self.send(ProcessError::UnknownError(e)), + }, + } + + Ok(()) + } + + fn finish_login(&self) { + self.sink().state(StateUpdate::LoggedIn(self.clone())); + self.send(AccountEvent::LoggedIn(self.name())); + } +} diff --git a/src/telegram/sessions/restore.rs b/src/telegram/sessions/restore.rs new file mode 100644 index 0000000..1aa389e --- /dev/null +++ b/src/telegram/sessions/restore.rs @@ -0,0 +1,74 @@ +use grammers_client::{Client, SenderPool}; +use grammers_session::storages::SqliteSession; +use log::{error, info}; +use std::sync::Arc; + +use crate::telegram::events::StateUpdate; +use crate::telegram::{AccountEvent, EventSink, ProcessError, TGClient}; +use crate::utils::get_api_keys; + +/// Tries to establish a connection to the local Telegram sqlite files +pub async fn connect_to_session(sink: EventSink, names: Vec) -> Result<(), ProcessError> { + let Some(api_data) = get_api_keys() else { + error!("No API keys found"); + return Err(ProcessError::InvalidAPIKeys); + }; + + let Ok(api_id) = api_data.api_id.parse() else { + error!("Failed to parse API ID. Given API ID: {}", api_data.api_id); + return Err(ProcessError::InvalidAPIKeys); + }; + + let mut successful_session = Vec::new(); + let mut failed_session = Vec::new(); + + let mut all_clients = Vec::new(); + + for name in names { + let name_without_sqlite = name.replace(".sqlite", ""); + + let session = SqliteSession::open(name).await; + + if let Err(e) = session { + error!("Failed to open session file: {e}"); + failed_session.push(name_without_sqlite); + continue; + } + + let session = Arc::new(session.unwrap()); + + let SenderPool { runner, handle, .. } = SenderPool::new(Arc::clone(&session), api_id); + tokio::spawn(runner.run()); + + let client = Client::new(handle); + + info!("Connected to Session {name_without_sqlite} successfully"); + + let authorized = client.is_authorized().await; + + let Ok(authorized) = authorized else { + info!("Failed to determine session authorization status {name_without_sqlite}"); + failed_session.push(name_without_sqlite); + continue; + }; + + info!("Session {name_without_sqlite} authorization status: {authorized}"); + + if !authorized { + failed_session.push(name_without_sqlite); + continue; + } + + let new_client = TGClient::new(client, name_without_sqlite.clone(), sink.clone(), false); + all_clients.push(new_client); + successful_session.push(name_without_sqlite); + } + + sink.state(StateUpdate::ClientsRestored(all_clients)); + sink.event(AccountEvent::SessionsRestored { + connected: successful_session, + failed: failed_session, + }); + + Ok(()) +} diff --git a/src/telegram/sessions/verify.rs b/src/telegram/sessions/verify.rs new file mode 100644 index 0000000..705ec5f --- /dev/null +++ b/src/telegram/sessions/verify.rs @@ -0,0 +1,60 @@ +use log::{error, info}; + +use crate::telegram::events::StateUpdate; +use crate::telegram::{AccountEvent, EventSink, ProcessError, TGClient, connect_to_session}; + +/// Returns the sessions that are still logged in. +/// +/// Sessions that were logged out since they connected are removed from the backend and +/// reported to the GUI. Sessions that could not be reached are only left out of the result +/// and stay connected. +pub async fn verify_sessions(clients: Vec) -> Vec { + let Some(sink) = clients.first().map(|client| client.sink().clone()) else { + return Vec::new(); + }; + + let mut usable = Vec::new(); + let mut dropped = Vec::new(); + + for client in clients { + match client.client().is_authorized().await { + Ok(true) => usable.push(client), + Ok(false) => { + info!( + "Session {} is no longer logged in. Dropping it", + client.name() + ); + dropped.push(client.name()); + } + Err(e) => { + error!( + "Could not check session {}, skipping it for now: {e}", + client.name() + ); + } + } + } + + if !dropped.is_empty() { + sink.state(StateUpdate::SessionsDropped(dropped.clone())); + sink.event(AccountEvent::SessionsDropped(dropped)); + } + + usable +} + +/// Drops sessions that got logged out and connects to saved sessions that are not connected yet +pub async fn refresh_sessions( + sink: EventSink, + clients: Vec, + new_files: Vec, +) -> Result<(), ProcessError> { + let working = verify_sessions(clients).await.len(); + + if new_files.is_empty() { + sink.event(AccountEvent::SessionsRefreshed { working }); + return Ok(()); + } + + connect_to_session(sink, new_files).await +} diff --git a/src/telegram/users/list.rs b/src/telegram/users/list.rs new file mode 100644 index 0000000..5d2febc --- /dev/null +++ b/src/telegram/users/list.rs @@ -0,0 +1,68 @@ +use grammers_session::types::PeerRef; +use log::{error, info}; + +use crate::telegram::{ProcessError, TGClient, UsersEvent}; +use crate::ui::state::{ListKind, UnpackedUser}; + +impl TGClient { + /// Resolves saved `PeerRef` values and sends them to the GUI + pub async fn load_list_users( + &self, + kind: ListKind, + peer_refs: Vec, + ) -> Result<(), ProcessError> { + info!( + "Starting resolving {} peers by {}", + kind.name(), + self.name() + ); + let mut peer_list = Vec::new(); + let mut failed_peer_num = 0; + + for peer_ref in peer_refs { + match self.client().resolve_peer(peer_ref).await { + Ok(peer) => peer_list.push(UnpackedUser::new(&peer, peer_ref, self.name())), + Err(e) => { + error!("Failed to resolve a peer. Error: {e}"); + failed_peer_num += 1; + } + } + } + + self.send(UsersEvent::ListLoaded { + kind, + users: peer_list, + failed: failed_peer_num, + }); + + Ok(()) + } + + /// Tries to get a Telegram user with the given username to add to a list + pub async fn add_list_user( + &self, + kind: ListKind, + chat_name: String, + ) -> Result<(), ProcessError> { + if !self.check_authorization().await? { + return Ok(()); + } + + let tg_chat = self.check_username(&chat_name).await?; + + let peer_ref = match tg_chat.to_ref().await { + Ok(Some(peer_ref)) => peer_ref, + _ => { + error!("Failed to get a reference of the peer"); + return Err(ProcessError::InvalidChat(chat_name)); + } + }; + + self.send(UsersEvent::ListAdded { + kind, + user: Box::new(UnpackedUser::new(&tg_chat, peer_ref, self.name())), + }); + + Ok(()) + } +} diff --git a/src/telegram/users/mod.rs b/src/telegram/users/mod.rs new file mode 100644 index 0000000..cb36772 --- /dev/null +++ b/src/telegram/users/mod.rs @@ -0,0 +1 @@ +mod list; diff --git a/src/tg_handler/blacklist.rs b/src/tg_handler/blacklist.rs deleted file mode 100644 index 468297f..0000000 --- a/src/tg_handler/blacklist.rs +++ /dev/null @@ -1,56 +0,0 @@ -use grammers_client::types::PackedChat; -use log::{error, info}; - -use crate::tg_handler::{ProcessError, ProcessResult, TGClient}; -use crate::ui_components::processor::UnpackedBlacklistedUser; - -impl TGClient { - /// Unpacks existing `PackedChat` hex string and sends it to the GUI - pub async fn load_blacklisted_users(&self, hex_data: Vec) -> Result<(), ProcessError> { - info!("Starting unpacking chat by {}", self.name()); - let mut chat_list = Vec::new(); - let mut failed_chat_num = 0; - - for hex in hex_data { - let packed_chat_result = PackedChat::from_hex(&hex); - - if let Ok(packed_chat) = packed_chat_result { - let chat = self.client().unpack_chat(packed_chat).await; - match chat { - Ok(chat) => chat_list.push(UnpackedBlacklistedUser::new(chat, self.name())), - Err(e) => { - error!("Failed to unpack a chat. Error: {e}"); - failed_chat_num += 1; - } - } - } else { - error!("Invalid chat hex found"); - failed_chat_num += 1; - } - } - - self.send(ProcessResult::UnpackedBlacklist(chat_list, failed_chat_num)); - Ok(()) - } - - /// Tries to get a Telegram chat with the given chat name - pub async fn new_blacklist(&self, chat_name: String) -> Result<(), ProcessError> { - if !self.check_authorization().await? { - return Ok(()); - } - - let tg_chat = self.check_username(&chat_name).await; - - let tg_chat = match tg_chat { - Ok(chat) => chat, - Err(e) => { - self.send(e); - return Ok(()); - } - }; - self.send(ProcessResult::BlackListUser(Box::new( - UnpackedBlacklistedUser::new(tg_chat, self.name()), - ))); - Ok(()) - } -} diff --git a/src/tg_handler/communication.rs b/src/tg_handler/communication.rs deleted file mode 100644 index 7a31e68..0000000 --- a/src/tg_handler/communication.rs +++ /dev/null @@ -1,62 +0,0 @@ -use grammers_client::types::iter_buffer::InvocationError; -use grammers_client::types::{LoginToken, PasswordToken}; -use grammers_mtsender::AuthorizationError; -use std::sync::Arc; -use std::sync::atomic::AtomicBool; -use tokio::sync::Mutex; - -use crate::tg_handler::{TGClient, TGCountData}; -use crate::ui_components::processor::{UnpackedBlacklistedUser, UnpackedWhitelistedUser}; - -#[allow(clippy::large_enum_variant)] -pub enum ProcessResult { - InitialSessionSuccess((Vec, Vec, Vec)), - InvalidChat(String), - UnauthorizedClient(String), - CountingMessage(Box), - CountingEnd((i32, i32)), - ProcessFailed(ProcessError), - LoginCodeSent(LoginToken, TGClient), - PasswordRequired(Box), - LoggedIn(String), - UnpackedWhitelist(Vec, i32), - UnpackedBlacklist(Vec, i32), - FloodWait, - WhiteListUser(Box), - BlackListUser(Box), - ChatExists(String, i32, i32), -} - -#[derive(Debug)] -pub enum ProcessError { - AuthorizationError, - FileCreationError, - InvalidTGCode, - InvalidPassword, - NotSignedUp, - InvalidPhoneOrAPI(AuthorizationError), - InvalidAPIKeys, - FailedLatestMessage, - UnknownError(InvocationError), -} - -/// Used by `TGClient` struct to handle operations -pub enum ProcessStart { - /// Start chat, start num, end num, multi session, whether to cancel - StartCount(String, Option, Option, bool, Arc), - SignInCode(Arc>, String), - SignInPasswords(Arc>, String), - SessionLogout, - LoadWhitelistedUsers(Vec), - LoadBlacklistedUsers(Vec), - NewWhitelistUser(String), - NewBlacklistUser(String), - /// Start chat, start num, end num - CheckChatExistence(String, Option, Option), -} - -/// Used when trying to create a new `TGClient` by processing some operations -pub enum NewProcess { - SendLoginCode(String, String, bool), - InitialSessionConnect(Vec), -} diff --git a/src/tg_handler/handler.rs b/src/tg_handler/handler.rs deleted file mode 100644 index 22dd072..0000000 --- a/src/tg_handler/handler.rs +++ /dev/null @@ -1,161 +0,0 @@ -use eframe::egui::Context; -use grammers_client::Client; -use grammers_client::types::Chat; -use log::{error, info}; -use std::sync::mpsc::Sender; - -use crate::tg_handler::{ - NewProcess, ProcessError, ProcessResult, ProcessStart, connect_to_session, send_login_code, -}; - -#[derive(Clone)] -pub struct TGClient { - client: Client, - name: String, - sender: Sender, - context: Context, - is_temporary: bool, -} - -impl TGClient { - pub fn new( - client: Client, - name: String, - sender: Sender, - context: Context, - is_temporary: bool, - ) -> Self { - TGClient { - client, - name, - sender, - context, - is_temporary, - } - } - - /// Start an operation with a telegram client - pub async fn start_process(self, process_type: ProcessStart) { - let result = match process_type { - ProcessStart::StartCount(start_chat, start_num, end_num, multi_session, cancel) => { - self.start_count(start_chat, start_num, end_num, multi_session, cancel) - .await - } - ProcessStart::SignInCode(token, code) => self.sign_in_code(token, code).await, - ProcessStart::SignInPasswords(token, password) => { - self.sign_in_password(token, password).await - } - ProcessStart::SessionLogout => self.logout().await, - ProcessStart::LoadWhitelistedUsers(hex_data) => { - self.load_whitelisted_users(hex_data).await - } - ProcessStart::NewWhitelistUser(name) => self.new_whitelist(name).await, - ProcessStart::LoadBlacklistedUsers(hex_data) => { - self.load_blacklisted_users(hex_data).await - } - ProcessStart::NewBlacklistUser(name) => self.new_blacklist(name).await, - ProcessStart::CheckChatExistence(name, start, end) => { - self.check_chat_status(name, start, end).await - } - }; - - if let Err(err) = result { - error!("Error acquired while handing a process: {err:?}"); - self.send(ProcessResult::ProcessFailed(err)); - } - } - - pub fn name(&self) -> String { - self.name.clone() - } - - /// Sends a process result to the GUI side, the only way to communicate with the GUI from async - pub fn send(&self, data: ProcessResult) { - self.sender.send(data).unwrap(); - self.context.request_repaint(); - } - - pub fn client(&self) -> &Client { - &self.client - } - - pub fn is_temporary(&self) -> bool { - self.is_temporary - } - - pub fn sender(&self) -> Sender { - self.sender.clone() - } - - pub fn context(&self) -> Context { - self.context.clone() - } - - /// Verifies if the current client is authorized for usage - pub async fn check_authorization(&self) -> Result { - let authorized: bool = self - .client() - .is_authorized() - .await - .map_err(ProcessError::UnknownError)?; - - info!("Client authorization status: {authorized}"); - - if !authorized { - self.send(ProcessResult::UnauthorizedClient(self.name())); - return Ok(false); - } - Ok(true) - } - - /// Tries to resolve a username to get a Telegram chat account - pub async fn check_username(&self, chat_name: &str) -> Result { - let tg_chat = self.client().resolve_username(chat_name).await; - - let Ok(tg_chat) = tg_chat else { - error!("Failed to resolve username"); - return Err(ProcessResult::InvalidChat(chat_name.to_owned())); - }; - - let Some(tg_chat) = tg_chat else { - error!("Found None value for target chat. Stopping processing"); - return Err(ProcessResult::InvalidChat(chat_name.to_owned())); - }; - - info!("Target chat {} exist", tg_chat.name()); - - Ok(tg_chat) - } - - /// Logs out of the client - pub async fn logout(&self) -> Result<(), ProcessError> { - let _ = self.client().sign_out().await; - info!("Logged out of client {}", self.name()); - Ok(()) - } -} - -/// Start a process that will result in the creation of a `TGClient` if successful -pub async fn start_process(process: NewProcess, sender: Sender, context: Context) { - let result = match process { - NewProcess::InitialSessionConnect(name) => { - connect_to_session(sender.clone(), name, &context).await - } - NewProcess::SendLoginCode(session_name, phone_number, is_temporary) => { - send_login_code( - sender.clone(), - &context, - session_name, - phone_number, - is_temporary, - ) - .await - } - }; - - if let Err(err) = result { - error!("Error acquired while handing a process: {err:?}"); - sender.send(ProcessResult::ProcessFailed(err)).unwrap(); - context.request_repaint(); - } -} diff --git a/src/tg_handler/initial_session.rs b/src/tg_handler/initial_session.rs deleted file mode 100644 index 5b22db6..0000000 --- a/src/tg_handler/initial_session.rs +++ /dev/null @@ -1,87 +0,0 @@ -use eframe::egui::Context; -use grammers_client::{Client, Config, InitParams}; -use grammers_session::Session; -use log::{error, info}; -use std::sync::mpsc::Sender; - -use crate::tg_handler::{ProcessError, ProcessResult, TGClient}; -use crate::utils::get_api_keys; - -/// Tries to establish a connection to the local Telegram session files -pub async fn connect_to_session( - sender: Sender, - names: Vec, - context: &Context, -) -> Result<(), ProcessError> { - let Some(api_data) = get_api_keys() else { - error!("No API keys found"); - return Err(ProcessError::InvalidAPIKeys); - }; - - let Ok(api_id) = api_data.api_id.parse() else { - error!("Failed to parse API ID. Given API ID: {}", api_data.api_id); - return Err(ProcessError::InvalidAPIKeys); - }; - let api_hash = api_data.api_hash; - - let mut successful_session = Vec::new(); - let mut failed_session = Vec::new(); - - let mut all_clients = Vec::new(); - - for name in names { - let name_without_session = name.replace(".session", ""); - - let client = Client::connect(Config { - session: Session::load_file_or_create(&name) - .map_err(|_| ProcessError::FileCreationError)?, - api_id, - api_hash: api_hash.clone(), - params: InitParams::default(), - }) - .await; - - let Ok(client) = client else { - info!("Failed to connect to session {name_without_session}"); - failed_session.push(name_without_session); - continue; - }; - - info!("Connected to Session {name_without_session} successfully"); - - let authorized = client.is_authorized().await; - - let Ok(authorized) = authorized else { - info!("Failed to determine session authorization status {name_without_session}"); - failed_session.push(name_without_session); - continue; - }; - - info!("Session {name_without_session} authorization status: {authorized}"); - - if !authorized { - failed_session.push(name_without_session); - continue; - } - - let new_client = TGClient::new( - client, - name_without_session.clone(), - sender.clone(), - context.clone(), - false, - ); - all_clients.push(new_client); - successful_session.push(name_without_session); - } - - sender - .send(ProcessResult::InitialSessionSuccess(( - all_clients, - successful_session, - failed_session, - ))) - .unwrap(); - context.request_repaint(); - Ok(()) -} diff --git a/src/tg_handler/mod.rs b/src/tg_handler/mod.rs deleted file mode 100644 index 95bf26f..0000000 --- a/src/tg_handler/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod blacklist; -mod communication; -mod counter; -mod handler; -mod initial_session; -mod new_session; -mod whitelist; - -pub use communication::*; -pub use counter::*; -pub use handler::*; -pub use initial_session::*; -pub use new_session::*; diff --git a/src/tg_handler/new_session.rs b/src/tg_handler/new_session.rs deleted file mode 100644 index b0a4304..0000000 --- a/src/tg_handler/new_session.rs +++ /dev/null @@ -1,151 +0,0 @@ -use eframe::egui::Context; -use grammers_client::types::{LoginToken, PasswordToken}; -use grammers_client::{Client, Config, FixedReconnect, InitParams, SignInError}; -use grammers_session::Session; -use log::{error, info}; -use std::fs; -use std::sync::Arc; -use std::sync::mpsc::Sender; -use tokio::sync::Mutex; - -use crate::tg_handler::{ProcessError, ProcessResult, TGClient}; -use crate::utils::get_api_keys; - -/// Tries to send Telegram login code to the given phone number -pub async fn send_login_code( - sender: Sender, - context: &Context, - session_name: String, - phone_number: String, - is_temporary: bool, -) -> Result<(), ProcessError> { - let Some(api_data) = get_api_keys() else { - error!("No API keys found"); - return Err(ProcessError::InvalidAPIKeys); - }; - - let Ok(api_id) = api_data.api_id.parse() else { - error!("Failed to parse API ID. Given API ID: {}", api_data.api_id); - return Err(ProcessError::InvalidAPIKeys); - }; - let api_hash = api_data.api_hash; - - let session = if is_temporary { - Session::new() - } else { - let target_path = format!("./{session_name}.session"); - - if fs::metadata(&target_path).is_ok() { - info!("{target_path} exists. Removing old session file"); - fs::remove_file(&target_path).unwrap(); - } - - Session::load_file_or_create(target_path).unwrap() - }; - - let reconnection = Box::leak(Box::new(FixedReconnect { - attempts: 10, - delay: std::time::Duration::from_secs(1), - })); - - let client = Client::connect(Config { - session, - api_id, - api_hash, - params: InitParams { - reconnection_policy: reconnection, - update_queue_limit: Some(1), - ..Default::default() - }, - }) - .await - .map_err(|_| ProcessError::AuthorizationError)?; - - let code_token = client - .request_login_code(&phone_number) - .await - .map_err(ProcessError::InvalidPhoneOrAPI)?; - - let new_client = TGClient::new(client, session_name, sender, context.clone(), is_temporary); - - new_client.send(ProcessResult::LoginCodeSent(code_token, new_client.clone())); - Ok(()) -} - -impl TGClient { - /// Tries to sign in to a Telegram account with the given Telegram login code - pub async fn sign_in_code( - &self, - token: Arc>, - code: String, - ) -> Result<(), ProcessError> { - let token = token.lock().await; - - let result = self.client().sign_in(&token, &code).await; - - match result { - Ok(_) => { - if !self.is_temporary() { - info!("Saving session data to a file"); - let target_path = format!("./{}.session", self.name()); - self.client().session().save_to_file(target_path).unwrap(); - } - self.send(ProcessResult::LoggedIn(self.name())); - } - Err(err) => match err { - SignInError::InvalidCode => { - self.send(ProcessResult::ProcessFailed(ProcessError::InvalidTGCode)); - } - SignInError::PasswordRequired(token) => { - self.send(ProcessResult::PasswordRequired(Box::new(token))); - } - SignInError::SignUpRequired { - terms_of_service: _, - } => self.send(ProcessResult::ProcessFailed(ProcessError::NotSignedUp)), - SignInError::InvalidPassword => unreachable!(), - SignInError::Other(e) => { - self.send(ProcessResult::ProcessFailed(ProcessError::UnknownError(e))); - } - }, - } - Ok(()) - } - - /// Tries to sign in to a Telegram account with the given login password. - /// May continue to fail if the first time password was not correct - pub async fn sign_in_password( - &self, - token: Arc>, - password: String, - ) -> Result<(), ProcessError> { - let token = token.lock().await.clone(); - - let result = self.client().check_password(token, password).await; - - match result { - Ok(_) => { - if !self.is_temporary() { - info!("Saving session data to a file"); - let target_path = format!("./{}.session", self.name()); - self.client().session().save_to_file(target_path).unwrap(); - } - self.send(ProcessResult::LoggedIn(self.name())); - } - Err(err) => match err { - SignInError::InvalidCode - | SignInError::PasswordRequired(_) - | SignInError::SignUpRequired { - terms_of_service: _, - } => unreachable!(), - SignInError::InvalidPassword => { - self.send(ProcessResult::ProcessFailed(ProcessError::InvalidPassword)); - } - SignInError::Other(e) => { - self.send(ProcessResult::ProcessFailed(ProcessError::UnknownError(e))); - } - }, - } - - Ok(()) - } -} diff --git a/src/tg_handler/whitelist.rs b/src/tg_handler/whitelist.rs deleted file mode 100644 index 5cdc5cd..0000000 --- a/src/tg_handler/whitelist.rs +++ /dev/null @@ -1,56 +0,0 @@ -use grammers_client::types::PackedChat; -use log::{error, info}; - -use crate::tg_handler::{ProcessError, ProcessResult, TGClient}; -use crate::ui_components::processor::UnpackedWhitelistedUser; - -impl TGClient { - /// Unpacks existing `PackedChat` hex string and sends it to the GUI - pub async fn load_whitelisted_users(&self, hex_data: Vec) -> Result<(), ProcessError> { - info!("Starting unpacking chat by {}", self.name()); - let mut chat_list = Vec::new(); - let mut failed_chat_num = 0; - - for hex in hex_data { - let packed_chat_result = PackedChat::from_hex(&hex); - - if let Ok(packed_chat) = packed_chat_result { - let chat = self.client().unpack_chat(packed_chat).await; - match chat { - Ok(chat) => chat_list.push(UnpackedWhitelistedUser::new(chat, self.name())), - Err(e) => { - error!("Failed to unpack a chat. Error: {e}"); - failed_chat_num += 1; - } - } - } else { - error!("Invalid chat hex found"); - failed_chat_num += 1; - } - } - - self.send(ProcessResult::UnpackedWhitelist(chat_list, failed_chat_num)); - Ok(()) - } - - /// Tries to get a Telegram chat with the given chat name - pub async fn new_whitelist(&self, chat_name: String) -> Result<(), ProcessError> { - if !self.check_authorization().await? { - return Ok(()); - } - - let tg_chat = self.check_username(&chat_name).await; - - let tg_chat = match tg_chat { - Ok(chat) => chat, - Err(e) => { - self.send(e); - return Ok(()); - } - }; - self.send(ProcessResult::WhiteListUser(Box::new( - UnpackedWhitelistedUser::new(tg_chat, self.name()), - ))); - Ok(()) - } -} diff --git a/src/ui/api_keys.rs b/src/ui/api_keys.rs new file mode 100644 index 0000000..95a857c --- /dev/null +++ b/src/ui/api_keys.rs @@ -0,0 +1,161 @@ +use eframe::egui::{ + Align, CentralPanel, Color32, Layout, RichText, ScrollArea, TextEdit, Ui, vec2, +}; +use serde::{Deserialize, Serialize}; + +use crate::ui::MainWindow; +use crate::ui::state::AppState; +use crate::ui::widgets::{Card, PrimaryButton}; +use crate::utils::save_api_keys; + +const TG_LINK: &str = "https://my.telegram.org/"; + +#[derive(Deserialize, Serialize, Default)] +pub struct TGKeys { + pub api_id: String, + pub api_hash: String, +} + +impl TGKeys { + /// Telegram API IDs are plain numbers + fn id_error(&self) -> Option<&'static str> { + let id = self.api_id.trim(); + if id.is_empty() { + None + } else if !id.chars().all(|c| c.is_ascii_digit()) { + Some("The API ID only contains digits") + } else { + None + } + } + + /// Telegram API hashes are 32 hexadecimal characters + fn hash_error(&self) -> Option<&'static str> { + let hash = self.api_hash.trim(); + if hash.is_empty() { + None + } else if !hash.chars().all(|c| c.is_ascii_hexdigit()) { + Some("The API hash only contains 0-9 and a-f") + } else if hash.len() != 32 { + Some("The API hash is 32 characters long") + } else { + None + } + } + + fn is_valid(&self) -> bool { + !self.api_id.trim().is_empty() + && !self.api_hash.trim().is_empty() + && self.id_error().is_none() + && self.hash_error().is_none() + } +} + +impl MainWindow { + pub fn show_tg_keys_ui(&mut self, ui: &mut Ui) { + CentralPanel::default().show(ui, |ui| { + // Keep the form at a readable width on wide windows + let width = ui.available_width().min(520.0); + let side = ((ui.available_width() - width) / 2.0).max(0.0); + + // The window starts small, so let the form scroll instead of being cut off + ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.horizontal_top(|ui| { + ui.add_space(side); + ui.vertical(|ui| { + ui.set_width(width); + self.api_keys_form(ui); + }); + }); + }); + }); + } + + fn api_keys_form(&mut self, ui: &mut Ui) { + ui.add_space(8.0); + ui.label(RichText::new("Connect to Telegram").heading()); + ui.label( + RichText::new( + "Talon needs your own Telegram API key to read your chats. \ + It is saved on this device only and never shared.", + ) + .weak(), + ); + ui.add_space(12.0); + + Card::new().title("GET YOUR KEY").show(ui, |ui| { + let steps = [ + "Log in with your phone number", + "Open API development tools", + "Create a new application, any name works", + "Copy the api_id and api_hash it shows", + ]; + for (i, step) in steps.iter().enumerate() { + ui.horizontal(|ui| { + ui.label(RichText::new(format!("{}.", i + 1)).weak()); + ui.label(*step); + }); + } + ui.add_space(6.0); + if ui.link(format!("Open {TG_LINK}")).clicked() { + let _ = open::that(TG_LINK); + } + }); + + ui.add_space(8.0); + + Card::new().title("YOUR KEY").show(ui, |ui| { + ui.label("API ID"); + ui.add( + TextEdit::singleline(&mut self.tg_keys.api_id) + .hint_text("12345678") + .desired_width(f32::INFINITY), + ); + field_error(ui, self.tg_keys.id_error()); + + ui.add_space(6.0); + + ui.label("API Hash"); + ui.add( + TextEdit::singleline(&mut self.tg_keys.api_hash) + .hint_text("0123456789abcdef0123456789abcdef") + .password(true) + .desired_width(f32::INFINITY), + ); + field_error(ui, self.tg_keys.hash_error()); + }); + + ui.add_space(14.0); + + let valid = self.tg_keys.is_valid(); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = + PrimaryButton::new("Save and Continue").size(vec2(ui.available_width(), 40.0)); + let response = ui.add_enabled(valid, button); + let response = if valid { + response + } else { + response.on_disabled_hover_text("Enter a valid API ID and API hash first") + }; + if response.clicked() { + self.tg_keys.api_id = self.tg_keys.api_id.trim().to_string(); + self.tg_keys.api_hash = self.tg_keys.api_hash.trim().to_string(); + save_api_keys(&self.tg_keys); + self.app_state = AppState::InitializedUI; + } + }); + } +} + +/// Small red hint under a field, takes no space when there is nothing to say +fn field_error(ui: &mut Ui, error: Option<&str>) { + if let Some(error) = error { + ui.label( + RichText::new(error) + .small() + .color(Color32::from_rgb(214, 90, 90)), + ); + } +} diff --git a/src/ui_components/initializer.rs b/src/ui/app.rs similarity index 68% rename from src/ui_components/initializer.rs rename to src/ui/app.rs index c76950c..bb38698 100644 --- a/src/ui_components/initializer.rs +++ b/src/ui/app.rs @@ -1,32 +1,27 @@ use eframe::egui::{Panel, Ui}; use eframe::{App, CreationContext, Frame, egui}; use egui::{ - Align, Button, CentralPanel, Context, CornerRadius, FontData, FontDefinitions, FontFamily, Id, - Layout, Modal, ScrollArea, Spinner, ThemePreference, ViewportCommand, Visuals, + Align, Button, CentralPanel, Id, Layout, Modal, ProgressBar, ScrollArea, Spinner, + ThemePreference, ViewportCommand, Visuals, }; use egui_theme_lerp::ThemeAnimator; -use log::info; -use std::collections::{BTreeMap, HashMap}; +use std::collections::HashMap; use std::slice::IterMut; -use std::sync::atomic::AtomicBool; -use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; +use std::time::Duration; use strum::IntoEnumIterator; -use tokio::runtime::Runtime; -use crate::tg_handler::{NewProcess, ProcessResult, ProcessStart, TGClient, start_process}; -use crate::ui_components::TGKeys; -use crate::ui_components::processor::{ - AppState, CounterCounts, ParsedChat, ProcessState, TabState, check_version, download_font, -}; -use crate::ui_components::tab_ui::{ - BlacklistData, ChartsData, CounterData, SessionData, UserTableData, WhitelistData, -}; -use crate::ui_components::widgets::AnimatedLabel; -use crate::utils::{ - find_session_files, get_api_keys, get_font_data, get_runtime, last_theme, save_theme, - theme_hover_text, +use crate::telegram::{Backend, Command}; +use crate::ui::TGKeys; +use crate::ui::services::check_version; +use crate::ui::state::{ + AppState, CounterCounts, ListKind, ParsedChat, ProcessState, Severity, TabState, }; +use crate::ui::tabs::{ChartsData, CounterData, SessionData, UserListData, UserTableData}; +use crate::ui::widgets::{StatusLine, TabStyle, Tabs}; +use crate::utils::{find_session_files, get_api_keys, last_theme, save_theme, theme_hover_text}; + +const STATUS_FADE_SECONDS: f64 = 6.0; pub struct MainWindow { pub app_state: AppState, @@ -35,15 +30,15 @@ pub struct MainWindow { table: Vec, chart: Vec, pub session: SessionData, - pub whitelist: WhitelistData, - pub blacklist: BlacklistData, + pub whitelist: UserListData, + pub blacklist: UserListData, tab_state: TabState, pub process_state: ProcessState, - pub tg_sender: Sender, - pub tg_receiver: Receiver, - pub tg_clients: BTreeMap, - pub incomplete_tg_client: Option, existing_sessions_checked: bool, + /// Saved whitelist and blacklist are only loaded once, after the first connection + pub saved_lists_loaded: bool, + status_text: String, + status_changed_at: f64, is_light_theme: bool, pub is_processing: bool, new_version_body: Arc>>, @@ -51,12 +46,35 @@ pub struct MainWindow { pub table_chat_index: usize, pub chart_chat_index: usize, pub initial_chart_reset: bool, - pub cancel_count: Arc, pub theme_animator: ThemeAnimator, - pub runtime: Runtime, + pub backend: Backend, } impl MainWindow { + /// Success messages go back to idle after a few seconds. Warnings, errors and anything + /// that is still running stay until something else replaces them + fn fade_status(&mut self, ui: &Ui) { + let now = ui.input(|i| i.time); + let text = self.process_state.to_string(); + + if text != self.status_text { + self.status_text = text; + self.status_changed_at = now; + } + + if self.is_processing || self.process_state.severity() != Severity::Success { + return; + } + + let remaining = STATUS_FADE_SECONDS - (now - self.status_changed_at); + + if remaining <= 0.0 { + self.process_state = ProcessState::Idle; + } else { + ui.request_repaint_after(Duration::from_secs_f64(remaining)); + } + } + pub fn new(cc: &CreationContext) -> Self { let last_theme_light = last_theme().unwrap_or_default(); let mut animator = ThemeAnimator::new(Visuals::light(), Visuals::dark()); @@ -70,7 +88,6 @@ impl MainWindow { .options_mut(|a| a.theme_preference = ThemePreference::Dark); animator.theme_1_to_2 = false; } - let (sender, receiver) = channel(); Self { app_state: AppState::default(), @@ -79,16 +96,15 @@ impl MainWindow { // Default value with an existing one with default table: vec![UserTableData::default()], chart: vec![ChartsData::default()], - whitelist: WhitelistData::default(), - blacklist: BlacklistData::default(), + whitelist: UserListData::new(ListKind::Whitelist), + blacklist: UserListData::new(ListKind::Blacklist), session: SessionData::default(), tab_state: TabState::Counter, process_state: ProcessState::Idle, - tg_sender: sender, - tg_receiver: receiver, - tg_clients: BTreeMap::new(), - incomplete_tg_client: None, existing_sessions_checked: false, + saved_lists_loaded: false, + status_text: String::new(), + status_changed_at: 0.0, is_light_theme: last_theme_light, is_processing: false, new_version_body: Arc::new(Mutex::new(None)), @@ -96,9 +112,8 @@ impl MainWindow { table_chat_index: 0, chart_chat_index: 0, initial_chart_reset: false, - cancel_count: Arc::new(AtomicBool::new(false)), theme_animator: animator, - runtime: get_runtime(), + backend: Backend::new(cc.egui_ctx.clone()), } } } @@ -107,31 +122,11 @@ impl App for MainWindow { fn ui(&mut self, ui: &mut Ui, _: &mut Frame) { // If asked to close the app, search for any temporary client and if any, logout then close the window if ui.ctx().input(|i| i.viewport().close_requested()) { - let mut joins = Vec::new(); - for (_, client) in self.tg_clients.clone() { - if client.is_temporary() { - let joiner = self.runtime.spawn(async move { - client.start_process(ProcessStart::SessionLogout).await; - }); - joins.push(joiner); - } - } - - while !joins.is_empty() { - for (index, join) in joins.iter().enumerate() { - if join.is_finished() { - joins.remove(index); - break; - } - } - } + self.backend.logout_temporary_sessions(); } match self.app_state { - AppState::LoadingFontsAPI => { - ui.set_pixels_per_point(1.1); - self.set_fonts(ui); - + AppState::LoadingAPI => { // If API keys are found, start the main UI otherwise show the UI to input the API keys if get_api_keys().is_some() { self.app_state = AppState::InitializedUI; @@ -175,55 +170,62 @@ impl App for MainWindow { save_theme(self.is_light_theme); } - let hover_position = ui.make_persistent_id("tab_hover"); - let selected_position = ui.make_persistent_id("tab_selected"); - - for val in TabState::iter() { - let selected = self.tab_state == val; - let first_val = val == TabState::first_value(); - - let resp = ui.add(AnimatedLabel::new( - selected, - val.to_string(), - selected_position, - hover_position, - 70.0, - 20.0, - Some(CornerRadius::ZERO), - (first_val, true), - )); - - if resp.clicked() { - let window_size = val.window_size(); - ui.send_viewport_cmd(ViewportCommand::InnerSize(window_size)); - self.tab_state = val; - } + if let Some(tab) = + Tabs::new("main_tabs", TabState::iter(), &self.tab_state) + .style(TabStyle::Pill) + .min_item_width(70.0) + .centered(true) + .show(ui) + { + ui.send_viewport_cmd(ViewportCommand::InnerSize(tab.window_size())); + self.tab_state = tab; } }); + ui.add_space(0.5); }); + Panel::bottom("bottom_panel") .show_separator_line(true) .show(ui, |ui| { ui.add_space(4.0); + self.fade_status(ui); + let status_text = self.process_state.to_string(); + let dot = self.process_state.severity().dot_color(ui.visuals()); + + // The Scan tab already has its own progress bar + let show_progress = + self.counter.counting() && self.tab_state != TabState::Counter; + let show_spinner = self.is_processing && !self.counter.counting(); + ui.horizontal(|ui| { - ui.label(status_text); - if self.is_processing { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + // Right side items are added first so the text takes what is left + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if show_progress { + ui.add( + ProgressBar::new(self.counter.bar_percentage()) + .desired_width(180.0) + .show_percentage() + .animate(true), + ); + } else if show_spinner { ui.add(Spinner::new()); - }); - } + } + + ui.add(StatusLine::new(status_text, dot, ui.available_width())); + }); }); ui.add_space(0.5); }); + CentralPanel::default().show(ui, |ui| { match self.tab_state { TabState::Counter => self.show_counter_ui(ui), TabState::UserTable => self.show_user_table_ui(ui), TabState::Charts => self.show_charts_ui(ui), - TabState::Whitelist => self.show_whitelist_ui(ui), - TabState::Blacklist => self.show_blacklist_ui(ui), + TabState::Whitelist => self.show_list_ui(ui, ListKind::Whitelist), + TabState::Blacklist => self.show_list_ui(ui, ListKind::Blacklist), TabState::Session => self.show_session_ui(ui), } @@ -240,24 +242,16 @@ impl App for MainWindow { let existing_sessions = find_session_files(); if !existing_sessions.is_empty() { self.is_processing = true; - let sender_clone = self.tg_sender.clone(); - let ctx_clone = ui.ctx().clone(); - self.runtime.spawn(async move { - start_process( - NewProcess::InitialSessionConnect(existing_sessions), - sender_clone, - ctx_clone, - ) - .await; - }); + self.process_state = ProcessState::ConnectingSessions; + + self.backend + .send(Command::ConnectSavedSessions(existing_sessions)); } + let version_body = self.new_version_body.clone(); - self.runtime.spawn(async move { - check_version(version_body).await; - }); + self.backend.spawn(check_version(version_body)); } - if self.new_version_body.lock().unwrap().is_some() { let modal_text = self.new_version_body.lock().unwrap().clone().unwrap(); let modal = Modal::new(Id::unique("version_modal")).show(ui.ctx(), |ui| { @@ -302,6 +296,7 @@ impl App for MainWindow { }); }); }); + if modal.should_close() { *self.new_version_body.lock().unwrap() = None; } @@ -369,41 +364,7 @@ impl MainWindow { /// Get all the added session names pub fn get_session_names(&self) -> Vec { - self.tg_clients.keys().map(ToString::to_string).collect() - } - - /// Set the fonts for egui to use or download them if does not exist - pub fn set_fonts(&self, ctx: &Context) { - let font_data = get_font_data(); - - if let Some((cjk, gentium)) = font_data { - // Add the fonts on top of the default ones - let font_cjk = Arc::new(FontData::from_owned(cjk)); - let font_gentium = Arc::new(FontData::from_owned(gentium)); - let mut font_definitions = FontDefinitions::default(); - - font_definitions - .font_data - .insert("NotoSansCJK".to_owned(), font_cjk); - font_definitions - .font_data - .insert("GentiumBookPlus".to_owned(), font_gentium); - - font_definitions - .families - .get_mut(&FontFamily::Proportional) - .unwrap() - .extend(["NotoSansCJK".to_owned(), "GentiumBookPlus".to_owned()]); - - ctx.set_fonts(font_definitions); - } else { - info!("Could not find font data. Starting download"); - let ctx_clone = ctx.clone(); - - self.runtime.spawn(async move { - download_font(ctx_clone).await; - }); - } + self.backend.session_names() } /// Return the currently selected table data as mutable diff --git a/src/ui_components/processor/date_handler.rs b/src/ui/dates/handler.rs similarity index 81% rename from src/ui_components/processor/date_handler.rs rename to src/ui/dates/handler.rs index 7ef463d..1a76035 100644 --- a/src/ui_components/processor/date_handler.rs +++ b/src/ui/dates/handler.rs @@ -1,4 +1,3 @@ -use chrono::{Datelike, NaiveDate}; use jiff::civil::Date; /// Handler for the `DatePicker` in the UI for data changes @@ -18,23 +17,15 @@ pub struct DatePickerHandler { end: Option, } -pub trait NaiveToJiff { - fn to_jiff(&self) -> Date; -} - -impl NaiveToJiff for NaiveDate { - fn to_jiff(&self) -> Date { - Date::new(self.year() as i16, self.month() as i8, self.day() as i8).unwrap() - } -} - impl DatePickerHandler { pub fn from(&mut self) -> &mut Date { &mut self.from } + pub fn to(&mut self) -> &mut Date { &mut self.to } + /// Verify whether the current From and To dates have changed pub fn check_date_change(&mut self) -> bool { if let Some(d) = self.last_from @@ -70,8 +61,7 @@ impl DatePickerHandler { /// Compare the given date with the current Start and End date /// to find the oldest and the newest date - pub fn update_dates(&mut self, date: NaiveDate) { - let date = date.to_jiff(); + pub fn update_dates(&mut self, date: Date) { if self.start.is_none_or(|current| current > date) { self.from = date; self.start = Some(date); @@ -86,15 +76,12 @@ impl DatePickerHandler { } /// Whether the given date is whtin the current From and To range - pub fn within_range(&self, date: NaiveDate) -> bool { - let date = date.to_jiff(); - + pub fn within_range(&self, date: Date) -> bool { date >= self.from && date <= self.to } /// Whether the given date is before the current To range - pub fn before_to_range(&self, date: NaiveDate) -> bool { - let date = date.to_jiff(); + pub fn before_to_range(&self, date: Date) -> bool { date < self.to } } diff --git a/src/ui/dates/mod.rs b/src/ui/dates/mod.rs new file mode 100644 index 0000000..d05c7b7 --- /dev/null +++ b/src/ui/dates/mod.rs @@ -0,0 +1,5 @@ +mod handler; +mod navigator; + +pub use handler::*; +pub use navigator::*; diff --git a/src/ui_components/processor/date_navigator.rs b/src/ui/dates/navigator.rs similarity index 98% rename from src/ui_components/processor/date_navigator.rs rename to src/ui/dates/navigator.rs index 71ebfaa..2e34ff7 100644 --- a/src/ui_components/processor/date_navigator.rs +++ b/src/ui/dates/navigator.rs @@ -1,6 +1,7 @@ use jiff::ToSpan; -use crate::ui_components::processor::{DatePickerHandler, NavigationType}; +use crate::ui::dates::DatePickerHandler; +use crate::ui::state::NavigationType; #[derive(Default)] pub struct DateNavigator { diff --git a/src/ui/events/account.rs b/src/ui/events/account.rs new file mode 100644 index 0000000..281fb06 --- /dev/null +++ b/src/ui/events/account.rs @@ -0,0 +1,86 @@ +use log::info; +use std::fmt::Write as _; + +use crate::telegram::AccountEvent; +use crate::ui::MainWindow; +use crate::ui::state::{ListKind, ProcessState}; + +impl MainWindow { + pub(super) fn on_account_event(&mut self, event: AccountEvent) { + match event { + AccountEvent::SessionsRestored { connected, failed } => { + self.on_sessions_restored(connected, failed) + } + AccountEvent::LoginCodeSent => self.on_login_code_sent(), + AccountEvent::PasswordRequired => self.on_password_required(), + AccountEvent::LoggedIn(name) => self.on_logged_in(name), + AccountEvent::Unauthorized(client_name) => self.on_unauthorized(client_name), + AccountEvent::SessionsDropped(names) => self.on_sessions_dropped(names), + AccountEvent::SessionsRefreshed { working } => self.on_sessions_refreshed(working), + } + } + + fn on_sessions_restored(&mut self, connected: Vec, failed: Vec) { + let mut status_text = if connected.is_empty() { + String::new() + } else { + format!("Successfully connected to: {}.", connected.join(", ")) + }; + + let any_failed = !failed.is_empty(); + if any_failed { + let _ = write!(status_text, " Failed connection to: {}", failed.join(", ")); + } + + self.process_state = + ProcessState::InitialClientConnectionSuccessful(status_text, any_failed); + + // Reloading the lists would add every saved user a second time + if self.saved_lists_loaded { + self.stop_process(); + } else { + self.saved_lists_loaded = true; + self.load_saved_list(ListKind::Whitelist); + self.load_saved_list(ListKind::Blacklist); + } + } + + fn on_login_code_sent(&mut self) { + info!("Login code sent to the client"); + self.stop_process(); + self.session.code_sent = true; + self.process_state = ProcessState::TGCodeSent; + } + + fn on_password_required(&mut self) { + info!("Client requires a password authentication"); + self.stop_process(); + self.session.password_mode = true; + self.process_state = ProcessState::PasswordRequired; + } + + fn on_logged_in(&mut self, name: String) { + info!("Logged in to the client {name}"); + self.stop_process(); + self.session.reset_data(); + self.process_state = ProcessState::LoggedIn(name); + } + + fn on_unauthorized(&mut self, client_name: String) { + info!("{client_name} is not authorized."); + self.process_state = ProcessState::UnauthorizedClient(client_name); + self.stop_process(); + } + + fn on_sessions_dropped(&mut self, names: Vec) { + info!("Sessions removed because they are logged out: {names:?}"); + // The list got shorter, keep the selected session in range + self.counter.session_index = 0; + self.process_state = ProcessState::SessionsDropped(names.join(", ")); + } + + fn on_sessions_refreshed(&mut self, working: usize) { + self.stop_process(); + self.process_state = ProcessState::SessionsRefreshed(working); + } +} diff --git a/src/ui/events/failure.rs b/src/ui/events/failure.rs new file mode 100644 index 0000000..afbc5c5 --- /dev/null +++ b/src/ui/events/failure.rs @@ -0,0 +1,57 @@ +use log::{error, info}; + +use crate::telegram::ProcessError; +use crate::ui::MainWindow; +use crate::ui::state::ProcessState; + +impl MainWindow { + pub(super) fn on_failure(&mut self, err: ProcessError) { + match err { + ProcessError::FileCreationError => { + error!("Error acquired while trying to create/delete the session file"); + self.process_state = ProcessState::FileCreationFailed; + } + ProcessError::InvalidTGCode => { + error!("Invalid TG Code given for the session"); + self.process_state = ProcessState::InvalidTGCode; + } + ProcessError::NotSignedUp => { + error!("The phone number is not signed up"); + self.process_state = ProcessState::NotSignedUp; + } + ProcessError::UnknownError(e) => { + error!("Unknown error encountered while trying to complete the process. {e}"); + self.process_state = ProcessState::UnknownError; + } + ProcessError::InvalidPassword => { + error!("Invalid TG Password given for the session"); + self.process_state = ProcessState::InvalidPassword; + } + ProcessError::InvalidPhoneOrAPI(e) => { + error!("Possibly invalid phone number given or API keys error. Error: {e}"); + self.process_state = ProcessState::InvalidPhoneOrAPI; + } + ProcessError::InvalidAPIKeys => { + error!("Invalid API keys were given"); + self.process_state = ProcessState::InvalidAPIKeys; + } + ProcessError::InvalidChat(chat_name) => { + info!("Invalid chat name found: {chat_name}"); + self.process_state = ProcessState::NonExistingChat(chat_name); + } + ProcessError::NoUsableSession => { + error!("Every session is logged out or unreachable"); + self.process_state = ProcessState::NoUsableSession; + } + ProcessError::UnknownSession => { + error!("A command was sent to a session that does not exist"); + self.process_state = ProcessState::EmptySelectedSession; + } + ProcessError::FailedLatestMessage => { + error!("Failed to get the latest message ID"); + self.process_state = ProcessState::LatestMessageLoadingFailed; + } + } + self.go_next_or_stop(); + } +} diff --git a/src/ui/events/mod.rs b/src/ui/events/mod.rs new file mode 100644 index 0000000..70ad6d4 --- /dev/null +++ b/src/ui/events/mod.rs @@ -0,0 +1,38 @@ +mod account; +mod failure; +mod scan; +mod users; + +use crate::telegram::Event; +use crate::ui::MainWindow; + +impl MainWindow { + /// Handles one pending event from the Telegram side. Returns false when there was none + pub fn check_receiver(&mut self) -> bool { + let Some(event) = self.backend.poll() else { + return false; + }; + + match event { + Event::Account(event) => self.on_account_event(event), + Event::Scan(event) => self.on_scan_event(event), + Event::Users(event) => self.on_users_event(event), + Event::Failed(error) => self.on_failure(error), + } + true + } + + pub fn stop_process(&mut self) { + self.is_processing = false; + self.counter.counting_ended(); + } + + fn go_next_or_stop(&mut self) { + if self.counter.counting() { + self.counter.increment_ongoing(); + self.process_next_count(); + } else { + self.stop_process(); + } + } +} diff --git a/src/ui/events/scan.rs b/src/ui/events/scan.rs new file mode 100644 index 0000000..052ad41 --- /dev/null +++ b/src/ui/events/scan.rs @@ -0,0 +1,221 @@ +use jiff::tz::TimeZone; +use log::info; + +use crate::telegram::{Command, ScanEvent, TGCountData}; +use crate::ui::MainWindow; +use crate::ui::state::{ProcessState, peer_details}; +use crate::utils::to_chart_name; + +impl MainWindow { + pub(super) fn on_scan_event(&mut self, event: ScanEvent) { + match event { + ScanEvent::ChatChecked { + chat, + start, + end, + sessions, + } => self.on_chat_checked(chat, start, end, sessions), + ScanEvent::Message(count_data) => self.on_counted_message(*count_data), + ScanEvent::Finished { + end_at, + last_number, + } => self.on_count_finished(end_at, last_number), + ScanEvent::FloodWait => self.on_flood_wait(), + } + } + + fn on_chat_checked( + &mut self, + chat_name: String, + start_at: i32, + end_at: i32, + sessions: Vec, + ) { + // Because we count both the start and ending message ID + let total_to_count = start_at - end_at + 1; + let total_session = sessions.len(); + let per_session_value = total_to_count / total_session as i32; + + info!("Each session to process {per_session_value}~ messages"); + + self.counter.set_session_count(total_session); + + let mut ongoing_start_at = start_at; + let mut ongoing_end_at = start_at - per_session_value; + + let mut negative_added = false; + self.backend.reset_cancel(); + + for (index, session) in sessions.into_iter().enumerate() { + self.counter.add_session(session.clone()); + + if index == total_session - 1 { + ongoing_end_at = end_at; + } + + info!( + "{} start point {} end point {}", + session, ongoing_start_at, ongoing_end_at + ); + + self.backend.send(Command::StartCount { + session, + chat: chat_name.clone(), + start: Some(ongoing_start_at), + end: Some(ongoing_end_at), + multi_session: true, + }); + + ongoing_start_at -= per_session_value; + ongoing_end_at -= per_session_value; + + // because we count both starting and end point + // Example starting point 100, end point 1. Total session 4, per session to process 25 messages + // First session start at 100 end at 100 - 25 = 75 + // Next session start at (last session start - per session process) end at (last session end - per session process) + // + // Here start at would be 75 which will overlap a message so reduce 1 + // + // next session start at 49 end at 25 and so on + if !negative_added { + ongoing_start_at -= 1; + negative_added = true; + } + } + } + + fn on_counted_message(&mut self, count_data: TGCountData) { + self.process_state = self.process_state.next_dot(); + + let message = count_data.message(); + let start_from = count_data.start_at(); + let end_at = count_data.end_at(); + let last_number = count_data.last_number(); + let multi_session = count_data.multi_session(); + + // Group messages by the day and hour they were sent in the local time zone + let sent_at = message.date().to_zoned(TimeZone::system()); + let local_time_date = sent_at.date(); + let local_time_datetime = sent_at.datetime(); + + let sender = message.sender(); + + let user_id = sender.map_or(0, |peer| peer_details(peer).2); + + let blacklisted = self.blacklist.contains(user_id); + + let (user_id, full_name, user_name) = self.t_table().add_user( + sender, + count_data.sender_ref(), + local_time_date, + local_time_datetime, + count_data.name(), + blacklisted, + ); + + let chart_user = to_chart_name(user_name, &full_name, user_id); + + if blacklisted { + self.t_table().count_blacklisted_message(local_time_date); + } else { + self.t_chart().add_user(chart_user.clone(), user_id); + self.t_table().count_user_message( + user_id, + message, + local_time_date, + local_time_datetime, + ); + } + + let whitelisted = self.whitelist.contains(user_id); + + if user_id != 0 && whitelisted && !blacklisted { + self.t_table().set_as_whitelisted(&[user_id]); + } + + let total_user = self.t_table().get_total_users_full(); + self.t_count().set_total_user(total_user as i32); + + let total_to_iter = start_from - end_at; + let message_value = 100.0 / total_to_iter as f32; + + let current_message_number = message.id(); + + // If current num = 100 and last processed = 105 + // messages with 101, 102, 103 and 104 are missing/deleted + // The current num is already getting processed so subtract 1 + let total_deleted = if last_number == -1 { + 0 + } else { + (last_number - current_message_number) - 1 + }; + + self.t_count().add_deleted_message(total_deleted); + + let total_processed = start_from - current_message_number; + let processed_percentage = if total_processed != 0 { + total_processed as f32 * message_value + } else { + message_value + }; + + self.t_count().add_one_total_message(); + if whitelisted { + self.t_count().add_one_whitelisted_message(); + self.t_count().add_whitelisted_user(user_id); + } + + // In single session set the progress by explicitly by counting it on the go + // On multi session add whatever percentage there is + new value for this session + if multi_session { + self.counter + .set_session_percentage(&count_data.name(), processed_percentage / 100.0); + } else { + self.counter + .set_bar_percentage(processed_percentage / 100.0); + } + + if !blacklisted { + self.t_chart().add_message( + local_time_datetime, + local_time_date, + chart_user, + &count_data.name(), + ); + } + + if self.t_table().reload_count() > 100 { + self.t_table().create_rows(); + self.t_table().reset_reload_count(); + } + } + + fn on_count_finished(&mut self, end_at: i32, last_number: i32) { + // Example case end point 100, last processed 102 + // Current num 99 so end point reached + // 101 and 100 is missing so count them as deleted + if last_number != end_at { + let total_deleted = last_number - end_at; + self.t_count().add_deleted_message(total_deleted); + } + + info!("Counting ended for a session"); + + // Stop process sets the progress bar to 100 + // Progress only if 1 session is remaining to be completed or it was 0 (0 in normal counting) + // Also recreate table data after counting session ends for a chat + if self.counter.session_remaining() <= 1 { + self.t_table().create_rows(); + let total_user = self.t_table().get_total_users_full(); + self.t_count().set_total_user(total_user as i32); + self.go_next_or_stop(); + } else { + self.counter.reduce_session(); + } + } + + fn on_flood_wait(&mut self) { + info!("Flood wait triggered"); + self.process_state = ProcessState::FloodWait; + } +} diff --git a/src/ui/events/users.rs b/src/ui/events/users.rs new file mode 100644 index 0000000..b71d09e --- /dev/null +++ b/src/ui/events/users.rs @@ -0,0 +1,90 @@ +use log::info; + +use crate::telegram::UsersEvent; +use crate::ui::MainWindow; +use crate::ui::state::{ListKind, ProcessState, UnpackedUser}; +use crate::utils::to_chart_name; + +impl MainWindow { + pub(super) fn on_users_event(&mut self, event: UsersEvent) { + match event { + UsersEvent::ListLoaded { + kind, + users, + failed, + } => self.on_list_loaded(kind, users, failed), + UsersEvent::ListAdded { kind, user } => self.on_list_added(kind, *user), + } + } + + fn on_list_loaded(&mut self, kind: ListKind, users: Vec, failed: i32) { + let mut names = Vec::new(); + let mut user_ids = Vec::new(); + + for user in users { + names.push(to_chart_name(user.username.clone(), &user.name, user.id)); + user_ids.push(user.id); + + self.list_data(kind).add_user( + user.name, + user.username, + user.id, + user.peer_ref, + user.seen_by, + ); + } + self.is_processing = false; + + let list = self.list_data(kind); + list.increase_failed_by(failed); + let (total, failed_num) = (list.row_len(), list.failed_num()); + + if kind == ListKind::Blacklist { + self.hide_blacklisted(&names, &user_ids); + } + + self.process_state = ProcessState::ListLoaded(kind, total, failed_num); + } + + fn on_list_added(&mut self, kind: ListKind, user: UnpackedUser) { + self.stop_process(); + let user_id = user.id; + + info!("Adding {user_id} to {}", kind.name()); + + match kind { + ListKind::Whitelist => { + self.table().set_as_whitelisted(&[user_id]); + self.chart().reset_saved_bars(); + } + ListKind::Blacklist => { + let chart_name = to_chart_name(user.username.clone(), &user.name, user_id); + self.hide_blacklisted(&[chart_name], &[user_id]); + } + } + + let list = self.list_data(kind); + list.add_user( + user.name, + user.username, + user_id, + user.peer_ref, + user.seen_by, + ); + + list.clear_text_box(); + list.save(false); + self.process_state = ProcessState::ListUserAdded(kind); + } + + /// Removes the data of blacklisted users from every chart and table + fn hide_blacklisted(&mut self, chart_names: &[String], user_ids: &[i64]) { + for chart in self.chart_all() { + chart.clear_blacklisted(chart_names); + } + + for table in self.table_all() { + table.remove_blacklisted_rows(user_ids); + } + } +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs new file mode 100644 index 0000000..4297134 --- /dev/null +++ b/src/ui/mod.rs @@ -0,0 +1,11 @@ +mod api_keys; +mod app; +pub mod dates; +mod events; +pub mod services; +pub mod state; +pub mod tabs; +mod widgets; + +pub use api_keys::*; +pub use app::*; diff --git a/src/ui/services/mod.rs b/src/ui/services/mod.rs new file mode 100644 index 0000000..7a60bc3 --- /dev/null +++ b/src/ui/services/mod.rs @@ -0,0 +1,3 @@ +mod version; + +pub use version::*; diff --git a/src/ui_components/processor/version_checker.rs b/src/ui/services/version.rs similarity index 97% rename from src/ui_components/processor/version_checker.rs rename to src/ui/services/version.rs index 567e51e..7935152 100644 --- a/src/ui_components/processor/version_checker.rs +++ b/src/ui/services/version.rs @@ -2,10 +2,8 @@ use log::{error, info}; use reqwest::Error; use semver::Version; use serde::Deserialize; -use std::{ - sync::{Arc, Mutex}, - time::Duration, -}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; #[derive(Deserialize)] struct GithubRelease { diff --git a/src/ui_components/processor/counter_counts.rs b/src/ui/state/counter_counts.rs similarity index 100% rename from src/ui_components/processor/counter_counts.rs rename to src/ui/state/counter_counts.rs diff --git a/src/ui/state/mod.rs b/src/ui/state/mod.rs new file mode 100644 index 0000000..e90ec41 --- /dev/null +++ b/src/ui/state/mod.rs @@ -0,0 +1,7 @@ +mod counter_counts; +mod parsed_chat; +mod states; + +pub use counter_counts::*; +pub use parsed_chat::*; +pub use states::*; diff --git a/src/ui_components/processor/parsed_chat.rs b/src/ui/state/parsed_chat.rs similarity index 100% rename from src/ui_components/processor/parsed_chat.rs rename to src/ui/state/parsed_chat.rs diff --git a/src/ui/state/states.rs b/src/ui/state/states.rs new file mode 100644 index 0000000..8a98d57 --- /dev/null +++ b/src/ui/state/states.rs @@ -0,0 +1,447 @@ +use eframe::egui::{Color32, Vec2, Visuals, vec2}; +use grammers_client::peer::Peer; +use grammers_session::types::{PeerAuth, PeerId, PeerRef}; +use serde::{Deserialize, Serialize}; +use std::fmt::{self, Display as fDisplay}; +use strum_macros::{Display, EnumIter}; + +#[derive(Default)] +pub enum AppState { + #[default] + LoadingAPI, + InputAPIKeys, + InitializedUI, +} + +#[derive(PartialEq, EnumIter, Display)] +pub enum TabState { + #[strum(to_string = "Scan")] + Counter, + #[strum(to_string = "Users")] + UserTable, + Charts, + Whitelist, + Blacklist, + #[strum(to_string = "Accounts")] + Session, +} + +impl TabState { + pub fn window_size(&self) -> Vec2 { + match self { + TabState::Counter => vec2(550.0, 440.0), + TabState::UserTable => vec2(1250.0, 700.0), + TabState::Charts => vec2(1000.0, 700.0), + TabState::Whitelist | TabState::Blacklist => vec2(550.0, 600.0), + TabState::Session => vec2(550.0, 430.0), + } + } +} + +pub enum ProcessState { + Idle, + ConnectingSessions, + /// Connection summary and whether at least one session failed to connect + InitialClientConnectionSuccessful(String, bool), + Counting(u8), + InvalidStartChat, + DataCopied, + FileCreationFailed, + UnauthorizedClient(String), + NonExistingChat(String), + SendingTGCode, + TGCodeSent, + LogInWithCode, + LogInWithPassword, + InvalidTGCode, + InvalidPassword, + NotSignedUp, + UnknownError, + LoggedIn(String), + EmptySelectedSession, + /// Names of the sessions that were logged out and removed + SessionsDropped(String), + NoUsableSession, + /// Sessions that are logged in after a refresh + SessionsRefreshed(usize), + InvalidPhoneOrAPI, + InvalidAPIKeys, + PasswordRequired, + FloodWait, + /// Users from the users table were added to a list + UsersListed(ListKind, usize), + /// Saved users were loaded: (list, loaded, failed) + ListLoaded(ListKind, usize, i32), + ListLoadFailed(ListKind), + ListUsersRemoved(ListKind, usize), + ListCleared(ListKind), + ListUserAdded(ListKind), + LatestMessageLoadingFailed, + DataExported(String), +} + +/// How the status bar should present a `ProcessState` +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Severity { + Idle, + Busy, + Success, + Warning, + Error, +} + +impl Severity { + pub fn dot_color(self, visuals: &Visuals) -> Color32 { + match self { + Severity::Idle => visuals.weak_text_color(), + Severity::Busy => visuals.selection.bg_fill, + Severity::Success => Color32::from_rgb(76, 175, 110), + Severity::Warning => Color32::from_rgb(230, 160, 40), + Severity::Error => visuals.error_fg_color, + } + } +} + +impl ProcessState { + pub fn severity(&self) -> Severity { + match self { + ProcessState::Idle => Severity::Idle, + ProcessState::ConnectingSessions + | ProcessState::Counting(_) + | ProcessState::SendingTGCode + | ProcessState::LogInWithCode + | ProcessState::LogInWithPassword => Severity::Busy, + ProcessState::DataCopied + | ProcessState::TGCodeSent + | ProcessState::LoggedIn(_) + | ProcessState::UsersListed(..) + | ProcessState::ListUsersRemoved(..) + | ProcessState::ListCleared(_) + | ProcessState::ListUserAdded(_) + | ProcessState::DataExported(_) => Severity::Success, + ProcessState::SessionsRefreshed(_) => Severity::Success, + ProcessState::InitialClientConnectionSuccessful(_, failed) => { + if *failed { + Severity::Warning + } else { + Severity::Success + } + } + ProcessState::ListLoaded(_, _, failed) => { + if *failed > 0 { + Severity::Warning + } else { + Severity::Success + } + } + ProcessState::FloodWait + | ProcessState::PasswordRequired + | ProcessState::EmptySelectedSession + | ProcessState::SessionsDropped(_) => Severity::Warning, + ProcessState::InvalidStartChat + | ProcessState::FileCreationFailed + | ProcessState::UnauthorizedClient(_) + | ProcessState::NoUsableSession + | ProcessState::NonExistingChat(_) + | ProcessState::InvalidTGCode + | ProcessState::InvalidPassword + | ProcessState::NotSignedUp + | ProcessState::UnknownError + | ProcessState::InvalidPhoneOrAPI + | ProcessState::InvalidAPIKeys + | ProcessState::ListLoadFailed(_) + | ProcessState::LatestMessageLoadingFailed => Severity::Error, + } + } + + pub fn next_dot(&self) -> Self { + match self { + ProcessState::Counting(num) => { + let new_num = if num == &3 { 0 } else { num + 1 }; + ProcessState::Counting(new_num) + } + _ => ProcessState::Counting(0), + } + } +} + +impl fDisplay for ProcessState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ProcessState::Idle => write!(f, "Idle"), + ProcessState::ConnectingSessions => write!(f, "Connecting to saved sessions..."), + ProcessState::InitialClientConnectionSuccessful(text, _) => { + write!(f, "{text}",) + } + ProcessState::Counting(count) => { + write!(f, "Checking messages")?; + for _ in 0..*count { + write!(f, ".")?; + } + Ok(()) + } + ProcessState::InvalidStartChat => { + write!(f, "Could not detect any valid chat details") + } + ProcessState::DataCopied => { + write!(f, "Selected table data copied.") + } + ProcessState::FileCreationFailed => { + write!(f, "Could not create the session file. Try again") + } + ProcessState::UnauthorizedClient(name) => write!( + f, + "The session {name} is not authorized. Delete the session and create a new one" + ), + ProcessState::NonExistingChat(name) => { + write!(f, "The target chat {name} does not exist") + } + ProcessState::SendingTGCode => write!(f, "Trying to send Telegram login code"), + ProcessState::TGCodeSent => write!(f, "Telegram code was sent"), + ProcessState::LogInWithCode => { + write!(f, "Trying to login to the session with the code") + } + ProcessState::LogInWithPassword => { + write!(f, "Trying to login to the session with the password") + } + ProcessState::LoggedIn(name) => write!(f, "Logged in session {name}"), + ProcessState::InvalidTGCode => write!(f, "Invalid TG Code given"), + ProcessState::InvalidPassword => write!(f, "Invalid password given"), + ProcessState::NotSignedUp => { + write!(f, "Account not signed up with this phone number") + } + ProcessState::UnknownError => write!(f, "Unknown error acquired"), + ProcessState::EmptySelectedSession => write!( + f, + "No session is selected. Log in to an account from the Accounts tab" + ), + ProcessState::SessionsDropped(names) => write!( + f, + "Skipped logged out sessions: {names}. Log in again from the Accounts tab" + ), + ProcessState::SessionsRefreshed(total) => { + write!(f, "Sessions refreshed. {total} working") + } + ProcessState::NoUsableSession => write!( + f, + "No working session is available. Log in again from the Accounts tab" + ), + ProcessState::InvalidPhoneOrAPI => write!( + f, + "Unknown error acquired. Possibly invalid phone number given or API keys are invalid" + ), + ProcessState::InvalidAPIKeys => { + write!(f, "Failed to parse saved API keys. Are the API keys valid?") + } + ProcessState::PasswordRequired => { + write!(f, "Account requires a password authentication") + } + ProcessState::FloodWait => { + write!(f, "Flood wait triggered. Will resume again soon") + } + ProcessState::UsersListed(kind, num) => { + write!(f, "{} {num} users", kind.past_tense()) + } + ProcessState::ListLoaded(kind, success, failed) => write!( + f, + "Loaded {success} {} users. Failed to load {failed} users", + kind.adjective() + ), + ProcessState::ListLoadFailed(kind) => write!( + f, + "Failed to load {} users due to invalid saved data. Old data has been removed", + kind.adjective() + ), + ProcessState::ListUsersRemoved(kind, num) => { + write!(f, "{num} {} users removed", kind.adjective()) + } + ProcessState::ListCleared(kind) => { + write!(f, "All {} users removed", kind.adjective()) + } + ProcessState::ListUserAdded(kind) => write!(f, "User added to {}", kind.name()), + ProcessState::LatestMessageLoadingFailed => { + write!(f, "Failed to get the latest message") + } + ProcessState::DataExported(location) => { + write!(f, "Data exported to {location}") + } + } + } +} + +#[derive(EnumIter, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Copy, Display)] +pub enum ColumnName { + #[default] + Name, + Username, + #[strum(to_string = "User ID")] + UserID, + #[strum(to_string = "Total Message")] + TotalMessage, + #[strum(to_string = "Total Word")] + TotalWord, + #[strum(to_string = "Total Char")] + TotalChar, + #[strum(to_string = "Average Word")] + AverageWord, + #[strum(to_string = "Average Char")] + AverageChar, + #[strum(to_string = "First Message Seen")] + FirstMessageSeen, + #[strum(to_string = "Last Message Seen")] + LastMessageSeen, + Whitelisted, +} + +#[derive(Default, PartialEq, Clone, Copy, EnumIter, Display)] +pub enum ChartType { + #[default] + #[strum(to_string = "Messages")] + Message, + #[strum(to_string = "Active Users")] + ActiveUser, + #[strum(to_string = "Messages by Weekday")] + MessageWeekDay, + #[strum(to_string = "Users by Weekday")] + ActiveUserWeekDay, +} + +impl ChartType { + pub fn hover_text(&self) -> &'static str { + match self { + ChartType::Message => { + "Total count of messages in the selected time frame (e.g., hourly, daily, weekly)." + } + ChartType::ActiveUser => { + "Total count of active users in the selected time frame (e.g., hourly, daily, weekly)." + } + ChartType::MessageWeekDay => "Total count of messages for each day of the week.", + ChartType::ActiveUserWeekDay => "Total count of active users for each day of the week.", + } + } +} + +#[derive(Default, PartialEq, Copy, Clone, EnumIter, Display)] +pub enum ChartTiming { + #[default] + Hourly, + Daily, + Weekly, + Monthly, +} + +/// The two user lists that share the same behavior +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum ListKind { + Whitelist, + Blacklist, +} + +impl ListKind { + pub fn name(self) -> &'static str { + match self { + ListKind::Whitelist => "whitelist", + ListKind::Blacklist => "blacklist", + } + } + + pub fn adjective(self) -> &'static str { + match self { + ListKind::Whitelist => "whitelisted", + ListKind::Blacklist => "blacklisted", + } + } + + pub fn past_tense(self) -> &'static str { + match self { + ListKind::Whitelist => "Whitelisted", + ListKind::Blacklist => "Blacklisted", + } + } + + pub fn file_name(self) -> &'static str { + match self { + ListKind::Whitelist => "whitelist_v2.json", + ListKind::Blacklist => "blacklist_v2.json", + } + } +} + +/// Saved form of a `PeerRef`. +#[derive(Deserialize, Serialize, PartialEq, Eq, Hash)] +pub struct PackedUser { + pub peer_id: i64, + pub access_hash: i64, + pub seen_by: String, +} + +impl PackedUser { + /// Returns `None` if the peer has no id that can be saved + pub fn new(peer: PeerRef, seen_by: String) -> Option { + Some(Self { + peer_id: peer.id.bot_api_dialog_id()?, + access_hash: peer.auth.hash(), + seen_by, + }) + } + + pub fn peer_ref(&self) -> Option { + unpack_peer_ref(self.peer_id, self.access_hash) + } +} + +pub struct UnpackedUser { + pub name: String, + pub username: String, + pub id: i64, + pub peer_ref: PeerRef, + pub seen_by: String, +} + +impl UnpackedUser { + pub fn new(peer: &Peer, peer_ref: PeerRef, seen_by: String) -> Self { + let (name, username, id) = peer_details(peer); + Self { + name, + username, + id, + peer_ref, + seen_by, + } + } +} + +/// Rebuilds a `PeerRef` from the saved integers +fn unpack_peer_ref(peer_id: i64, access_hash: i64) -> Option { + Some(PeerRef { + id: PeerId::from_bot_api_dialog_id(peer_id)?, + auth: PeerAuth::from_hash(access_hash), + }) +} + +/// Returns the name, username and bare id of a peer +pub fn peer_details(peer: &Peer) -> (String, String, i64) { + // As per grammers lib doc, empty name can be given if it's a deleted account + let name = match peer { + Peer::User(user) => user.full_name(), + _ => peer.name().unwrap_or_default().to_string(), + }; + let name = if name.is_empty() { + "Deleted Account".to_string() + } else { + name + }; + + let username = peer.username().unwrap_or("Empty").to_string(); + + (name, username, peer.id().bare_id().unwrap_or(0)) +} + +#[derive(EnumIter, Default, PartialEq, Copy, Clone, Display)] +pub enum NavigationType { + #[default] + Day, + Week, + Month, + Year, +} diff --git a/src/ui/tabs/accounts.rs b/src/ui/tabs/accounts.rs new file mode 100644 index 0000000..a26e2ff --- /dev/null +++ b/src/ui/tabs/accounts.rs @@ -0,0 +1,242 @@ +use eframe::egui::{Align, Button, Checkbox, Grid, Label, Layout, TextEdit, Ui, vec2}; + +use crate::telegram::Command; +use crate::ui::MainWindow; +use crate::ui::state::ProcessState; +use crate::ui::widgets::{Card, PrimaryButton}; + +#[derive(Default)] +pub struct SessionData { + session_name: String, + phone_number: String, + tg_code: String, + tg_password: String, + is_temporary: bool, + /// A login code was sent and is waiting to be entered + pub code_sent: bool, + /// Whether the account asked for a password + pub password_mode: bool, +} + +impl SessionData { + fn get_session_name(&self) -> String { + self.session_name.clone() + } + + fn get_phone_number(&self) -> String { + self.phone_number.replace('+', "") + } + + fn get_password(&self) -> String { + self.tg_password.clone() + } + + fn get_is_temporary(&self) -> bool { + self.is_temporary + } + + fn get_tg_code(&self) -> String { + self.tg_code.clone() + } + + pub fn reset_data(&mut self) { + *self = Self::default(); + } +} + +impl MainWindow { + pub fn show_session_ui(&mut self, ui: &mut Ui) { + // Once a code was sent or a password is required, the account details are locked in + let locked = self.session.code_sent || self.session.password_mode; + + Card::new().show(ui, |ui| { + Grid::new("Session Grid") + .num_columns(2) + .spacing([8.0, 10.0]) + .show(ui, |ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.add(Label::new("Session Name:")); + }); + + let text_edit = TextEdit::singleline(&mut self.session.session_name) + .hint_text("My TG Session Name"); + + if locked { + ui.add_enabled(false, text_edit.min_size(ui.available_size())); + } else { + let hover_text = if self.session.is_temporary { + "A name for the temporary session" + } else { + "Save the session in a file with this name for later access" + }; + ui.add_sized(ui.available_size(), text_edit) + .on_hover_text(hover_text); + } + + ui.end_row(); + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.add(Label::new("Phone Number:")); + }); + + let text_edit = TextEdit::singleline(&mut self.session.phone_number) + .hint_text("International format: +1234567890"); + + if locked { + ui.add_enabled(false, text_edit.min_size(ui.available_size())); + } else { + ui.add_sized(ui.available_size(), text_edit).on_hover_text( + "The phone number of your Telegram in international format", + ); + } + + ui.end_row(); + + ui.label(""); + + let checkbox = Checkbox::new( + &mut self.session.is_temporary, + "Do not create a session file", + ); + + if self.session.code_sent || self.is_processing { + ui.add_enabled(false, checkbox); + } else { + ui.add(checkbox).on_hover_text( + "Create a new temporary session? +If yes, it will try to log out before the app is closed and no session file will be created", + ); + } + + ui.end_row(); + }); + }); + + ui.add_space(8.0); + + Card::new().show(ui, |ui| { + Grid::new("Verification Grid") + .num_columns(2) + .spacing([8.0, 10.0]) + .show(ui, |ui| { + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.add(Label::new("Login Code:")); + }); + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = Button::new("Send Code"); + if self.session.phone_number.is_empty() + || self.session.password_mode + || self.session.session_name.is_empty() + || self.is_processing + { + ui.add_enabled(false, button); + } else if ui + .add(button) + .on_hover_text("Send the code to login to the account") + .clicked() + { + self.request_login_code(); + } + + let text_edit = + TextEdit::singleline(&mut self.session.tg_code).hint_text("12345"); + + if self.session.code_sent { + ui.add_sized(ui.available_size(), text_edit).on_hover_text( + "The Telegram login code either sent to TG or to the phone number", + ); + } else { + ui.add_enabled(false, text_edit.min_size(ui.available_size())); + } + }); + + ui.end_row(); + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + ui.add(Label::new("Login Password:")); + }); + + let text_edit = TextEdit::singleline(&mut self.session.tg_password) + .password(true) + .hint_text("Only needed if the account has two-step verification"); + + if self.session.password_mode { + ui.add_sized(ui.available_size(), text_edit) + .on_hover_text("Telegram login password"); + } else { + ui.add_enabled(false, text_edit.min_size(ui.available_size())); + } + + ui.end_row(); + }); + }); + + ui.add_space(12.0); + + ui.horizontal(|ui| { + if ui + .add(Button::new("Reset").min_size(vec2(80.0, 40.0))) + .on_hover_text("Reset and clear new session creation data") + .clicked() + { + self.session.reset_data(); + self.backend.cancel_login(); + } + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = PrimaryButton::new("Log In").size(vec2(ui.available_width(), 40.0)); + if self.is_processing + || self.session.phone_number.is_empty() + || self.session.session_name.is_empty() + || self.session.tg_code.is_empty() + || (self.session.password_mode && self.session.tg_password.is_empty()) + { + ui.add_enabled(false, button); + } else if ui + .add(button) + .on_hover_text("Try to log in with the Telegram login info") + .clicked() + { + if self.session.password_mode { + self.sign_in_password(); + } else { + self.sign_in_code(); + } + } + }); + }); + } + + /// Asks Telegram to send a login code to the phone number + fn request_login_code(&mut self) { + self.is_processing = true; + self.process_state = ProcessState::SendingTGCode; + + self.backend.send(Command::RequestLoginCode { + session: self.session.get_session_name(), + phone: self.session.get_phone_number(), + temporary: self.session.get_is_temporary(), + }); + } + + /// Tries to log in with the given login code + fn sign_in_code(&mut self) { + self.is_processing = true; + self.process_state = ProcessState::LogInWithCode; + + self.backend.send(Command::SubmitLoginCode { + code: self.session.get_tg_code(), + }); + } + + /// Tries to log in with the given login password + fn sign_in_password(&mut self) { + self.is_processing = true; + self.process_state = ProcessState::LogInWithPassword; + + self.backend.send(Command::SubmitPassword { + password: self.session.get_password(), + }); + } +} diff --git a/src/ui_components/tab_ui/charts.rs b/src/ui/tabs/charts.rs similarity index 69% rename from src/ui_components/tab_ui/charts.rs rename to src/ui/tabs/charts.rs index 24f633d..0b92c48 100644 --- a/src/ui_components/tab_ui/charts.rs +++ b/src/ui/tabs/charts.rs @@ -1,16 +1,27 @@ -use chrono::{Datelike, Days, Duration, Months, NaiveDate, NaiveDateTime, Timelike, Weekday}; -use eframe::egui::{CentralPanel, ComboBox, Id, Key, Modal, Panel, ScrollArea, TextEdit, Ui}; +use eframe::egui::{ + Align, ComboBox, Id, Key, Layout, Modal, RichText, ScrollArea, TextEdit, Ui, vec2, +}; use egui_extras::DatePickerButton; use egui_plot::{Bar, BarChart, HoverPosition, Legend, Plot}; +use jiff::civil::{Date, DateTime, DateTimeDifference}; +use jiff::{ToSpan, Unit}; use nucleo_matcher::Matcher; use nucleo_matcher::pattern::{CaseMatching, Normalization, Pattern}; use std::collections::{BTreeMap, BTreeSet, HashMap}; use strum::IntoEnumIterator; -use crate::ui_components::MainWindow; -use crate::ui_components::processor::{ChartTiming, ChartType, DateNavigator, NavigationType}; -use crate::ui_components::widgets::AnimatedLabel; -use crate::utils::{time_to_string, weekday_num_to_string}; +use crate::ui::MainWindow; +use crate::ui::dates::DateNavigator; +use crate::ui::state::{ChartTiming, ChartType, NavigationType}; +use crate::ui::widgets::{Card, PrimaryButton, TabStyle, Tabs}; +use crate::utils::{format_datetime, time_to_string, weekday_num_to_string}; + +const TOTAL_DATA: &str = "Show total data"; +const WHITELISTED_DATA: &str = "Show whitelisted data"; + +fn is_summary_series(name: &str) -> bool { + name == TOTAL_DATA || name == WHITELISTED_DATA +} #[derive(Default)] pub struct ChartsData { @@ -24,15 +35,15 @@ pub struct ChartsData { last_chart_type: ChartType, chart_timing: ChartTiming, added_to_chart: BTreeSet, - hourly_message: BTreeMap>, - daily_message: BTreeMap>, - weekly_message: BTreeMap>, - monthly_message: BTreeMap>, + hourly_message: BTreeMap>, + daily_message: BTreeMap>, + weekly_message: BTreeMap>, + monthly_message: BTreeMap>, weekday_message: BTreeMap>, - last_hour: HashMap>, - last_day: HashMap>, - last_week: HashMap>, - last_month: HashMap>, + last_hour: HashMap>, + last_day: HashMap>, + last_week: HashMap>, + last_month: HashMap>, user_ids: HashMap, /// Pre-saved Bars to for the hourly chart, used for both Message and User hourly_bars: Option>>, @@ -40,11 +51,11 @@ pub struct ChartsData { daily_bars: Option>>, date_nav: DateNavigator, /// Hover labels, key = x value in chart. Values = (date, total message, whitelist message) - labels: HashMap, + labels: HashMap, /// Hover labels for the hourly chart, key = x value in chart. Values = (date, total message, whitelist message) - hourly_labels: HashMap, + hourly_labels: HashMap, /// Hover labels for the daily chart, key = x value in chart. Values = (date, total message, whitelist message) - daily_labels: HashMap, + daily_labels: HashMap, } impl ChartsData { @@ -64,27 +75,17 @@ impl ChartsData { self.weekday_message.clear(); self.reset_saved_bars(); - let mut ongoing_value = Some(Weekday::Mon); - - while let Some(value) = ongoing_value { - self.weekday_message.insert(value as u8, HashMap::new()); - let next_day = value.succ(); - - if next_day == Weekday::Mon { - ongoing_value = None; - } else { - ongoing_value = Some(next_day); - } + // 0 is Monday and 6 is Sunday + for weekday in 0..7u8 { + self.weekday_message.insert(weekday, HashMap::new()); } // These two are added to the chart by default - self.added_to_chart.insert("Show total data".to_string()); - self.added_to_chart - .insert("Show whitelisted data".to_string()); + self.added_to_chart.insert(TOTAL_DATA.to_string()); + self.added_to_chart.insert(WHITELISTED_DATA.to_string()); + self.available_users.insert(TOTAL_DATA.to_string(), true); self.available_users - .insert("Show total data".to_string(), true); - self.available_users - .insert("Show whitelisted data".to_string(), true); + .insert(WHITELISTED_DATA.to_string(), true); self.date_nav = DateNavigator::default(); } @@ -107,53 +108,42 @@ impl ChartsData { } /// Takes a message creation time and the unique user to create necessary data to form a chart - pub fn add_message( - &mut self, - time: NaiveDateTime, - date: NaiveDate, - add_to: String, - client_name: &str, - ) { + pub fn add_message(&mut self, time: DateTime, date: Date, add_to: String, client_name: &str) { // Keep a common value among messages for example messages sent within the same hour, // reset the second and minute value to 0 so these messages can be grouped - let hourly_time = time.with_second(0).unwrap().with_minute(0).unwrap(); - let daily_time = time - .with_second(0) - .unwrap() - .with_minute(0) - .unwrap() - .with_hour(0) - .unwrap(); - let monthly_time = time - .with_second(0) - .unwrap() - .with_minute(0) - .unwrap() - .with_hour(0) - .unwrap() - .with_day(1) + let hourly_time = time + .with() + .minute(0) + .second(0) + .subsec_nanosecond(0) + .build() .unwrap(); - - let sent_on = time.weekday(); - - // We only care about the week number for this. Set it as Monday to keep a common ground - let week_day_name = Weekday::Mon; - let week_num = time.iso_week().week(); - let time_year = time.iso_week().year(); - - let weekly_time = NaiveDate::from_isoywd_opt(time_year, week_num, week_day_name) + let daily_time = time.date().at(0, 0, 0, 0); + let monthly_time = time.date().first_of_month().at(0, 0, 0, 0); + + // 0 is Monday and 6 is Sunday + let days_since_monday = time.date().weekday().to_monday_zero_offset(); + let sent_on = days_since_monday as u8; + + // We only care about the week number for this. Use the Monday of the week + // to keep a common ground + let weekly_time = time + .date() + .checked_sub(i64::from(days_since_monday).days()) .unwrap() - .and_hms_opt(0, 0, 0) - .unwrap(); + .at(0, 0, 0, 0); // If last day is January 10, current day is January 5, add January 6 to 9 with 0 value // Apply the same for all of them if let Some(Some(last_hour)) = self.last_hour.get_mut(client_name) { - let missing_hour = (*last_hour - hourly_time).num_hours(); + let missing_hour = last_hour + .since(DateTimeDifference::new(hourly_time).largest(Unit::Hour)) + .unwrap() + .get_hours(); let mut ongoing_hour = *last_hour; for _ in 0..missing_hour { - let to_add = ongoing_hour.checked_sub_signed(Duration::hours(1)).unwrap(); + let to_add = ongoing_hour.checked_sub(1.hour()).unwrap(); self.hourly_message.entry(to_add).or_default(); ongoing_hour = to_add; } @@ -164,11 +154,14 @@ impl ChartsData { } if let Some(Some(last_day)) = self.last_day.get_mut(client_name) { - let missing_day = (*last_day - daily_time).num_days(); + let missing_day = last_day + .since(DateTimeDifference::new(daily_time).largest(Unit::Day)) + .unwrap() + .get_days(); let mut ongoing_day = *last_day; for _ in 0..missing_day { - let to_add = ongoing_day.checked_sub_signed(Duration::days(1)).unwrap(); + let to_add = ongoing_day.checked_sub(1.day()).unwrap(); self.daily_message.entry(to_add).or_default(); ongoing_day = to_add; } @@ -179,11 +172,14 @@ impl ChartsData { } if let Some(Some(last_week)) = self.last_week.get_mut(client_name) { - let missing_week = (*last_week - weekly_time).num_weeks(); + let missing_week = last_week + .since(DateTimeDifference::new(weekly_time).largest(Unit::Week)) + .unwrap() + .get_weeks(); let mut ongoing_week = *last_week; for _ in 0..missing_week { - let to_add = ongoing_week.checked_sub_signed(Duration::weeks(1)).unwrap(); + let to_add = ongoing_week.checked_sub(1.week()).unwrap(); self.weekly_message.entry(to_add).or_default(); ongoing_week = to_add; } @@ -199,10 +195,11 @@ impl ChartsData { // All monthly date has the day set as 1. Reducing 2 days would take us to the previous month while ongoing_month > monthly_time { let to_add = ongoing_month - .checked_sub_signed(Duration::days(2)) + .checked_sub(2.days()) .unwrap() - .with_day(1) - .unwrap(); + .date() + .first_of_month() + .at(0, 0, 0, 0); self.monthly_message.entry(to_add).or_default(); ongoing_month = to_add; } @@ -228,7 +225,7 @@ impl ChartsData { let target_user = counter.entry(add_to.clone()).or_insert(0); *target_user += 1; - let counter = self.weekday_message.get_mut(&(sent_on as u8)).unwrap(); + let counter = self.weekday_message.get_mut(&sent_on).unwrap(); let target_user = counter.entry(add_to).or_insert(0); *target_user += 1; @@ -244,74 +241,106 @@ impl ChartsData { self.daily_labels.clear(); } + /// Users that can be picked in the customize view, without the total and whitelisted series + fn user_names(&self) -> Vec { + self.available_users + .keys() + .filter(|name| !is_summary_series(name)) + .cloned() + .collect() + } + + /// Switch the total or whitelisted series on or off right away + fn set_summary_series(&mut self, name: &str, shown: bool) { + self.available_users.insert(name.to_string(), shown); + if shown { + self.add_to_chart(name.to_string()); + } else { + self.remove_from_chart(name); + } + } + fn show_modal_popup(&mut self, ui: &mut Ui) { let response = Modal::new(Id::unique("customize_view")).show(ui.ctx(), |ui| { - ui.set_width(400.0); - ui.set_height(350.0); - Panel::top("customize_top_view").show(ui, |ui| { - ui.vertical_centered(|ui| { - ui.heading("Customize View"); - }); - }); + ui.set_width(420.0); - Panel::bottom(Id::unique("customize_bottom_view")).show(ui, |ui| { - ui.add_space(5.0); - ui.vertical_centered_justified(|ui| { - if ui.button("Confirm").clicked() { - self.modal_open = false; - self.search_text.clear(); - } - }) + ui.vertical_centered(|ui| { + ui.heading("Customize View"); }); + ui.add_space(8.0); - CentralPanel::default().show(ui, |ui| { - ui.horizontal(|ui| { - let text_edit = - TextEdit::singleline(&mut self.search_text).hint_text("Search user"); + let row_size = vec2(ui.available_width(), ui.spacing().interact_size.y); - ui.add(text_edit); + ui.allocate_ui_with_layout(row_size, Layout::right_to_left(Align::Center), |ui| { + if ui.button("Clear").clicked() { + self.use_filtered_users = false; + } - if ui.button("Search").clicked() { - self.use_filtered_users = true; - self.filtered_users.clear(); + if ui.button("Search").clicked() { + self.use_filtered_users = true; + self.filtered_users.clear(); - let all_keys = self.available_users.keys().cloned().collect::>(); - let pattern = Pattern::parse( - &self.search_text, - CaseMatching::Ignore, - Normalization::Smart, - ); - let matches = pattern.match_list(all_keys, &mut self.matcher); + let all_keys = self.user_names(); + let pattern = Pattern::parse( + &self.search_text, + CaseMatching::Ignore, + Normalization::Smart, + ); + let matches = pattern.match_list(all_keys, &mut self.matcher); - for (val, _) in matches { - self.filtered_users.insert(val); - } + for (val, _) in matches { + self.filtered_users.insert(val); } + } - if ui.button("Clear").clicked() { - self.use_filtered_users = false; - } - }); + ui.add_sized( + [ui.available_width(), ui.spacing().interact_size.y], + TextEdit::singleline(&mut self.search_text).hint_text("Search user"), + ); + }); + + ui.add_space(8.0); - ScrollArea::vertical().show(ui, |ui| { - if self.use_filtered_users { - for val in &self.filtered_users { - ui.horizontal(|ui| { + Card::new().show(ui, |ui| { + ScrollArea::vertical() + .max_height(300.0) + .auto_shrink([false, true]) + .show(ui, |ui| { + if self.use_filtered_users { + for val in &self.filtered_users { ui.checkbox(self.available_users.get_mut(val).unwrap(), val); - ui.allocate_space(ui.available_size()); - }); - } - } else { - let all_keys = self.available_users.keys().cloned().collect::>(); - for val in all_keys { - ui.horizontal(|ui| { + } + } else { + for val in self.user_names() { ui.checkbox(self.available_users.get_mut(&val).unwrap(), val); - ui.allocate_space(ui.available_size()); - }); + } } - } - }); + }); }); + + let selected = self + .available_users + .iter() + .filter(|(name, on)| **on && !is_summary_series(name)) + .count(); + + ui.add_space(4.0); + + ui.label( + RichText::new(format!( + "{selected} of {} selected", + self.user_names().len() + )) + .weak(), + ); + + ui.add_space(8.0); + + let size = vec2(ui.available_width(), 36.0); + if ui.add(PrimaryButton::new("Confirm").size(size)).clicked() { + self.modal_open = false; + self.search_text.clear(); + } }); if response.should_close() { @@ -334,9 +363,9 @@ impl ChartsData { fn message_whitelist_added(&self, row_len: usize) -> (bool, bool) { // If there are no whitelisted users, this will be considered as not-shown. Adds extra bars // to the ui => consume more power. - let whitelist = self.added_to_chart.contains("Show whitelisted data") && row_len > 0; + let whitelist = self.added_to_chart.contains(WHITELISTED_DATA) && row_len > 0; - (self.added_to_chart.contains("Show total data"), whitelist) + (self.added_to_chart.contains(TOTAL_DATA), whitelist) } pub fn clear_blacklisted(&mut self, names: &[String]) { @@ -390,65 +419,67 @@ impl MainWindow { && self.chart_i().chart_type != ChartType::ActiveUserWeekDay; ui.horizontal(|ui| { - ui.selectable_value( - &mut self.chart().chart_type, - ChartType::Message, - ChartType::Message.to_string(), - ).on_hover_text("Chart displaying the total count of messages in the selected time frame (e.g., hourly, daily, weekly)."); - ui.separator(); - ui.selectable_value( - &mut self.chart().chart_type, - ChartType::ActiveUser, - ChartType::ActiveUser.to_string(), - ).on_hover_text("Chart showing the total count of active users in the selected time frame (e.g., hourly, daily, weekly)."); - ui.separator(); - ui.selectable_value( - &mut self.chart().chart_type, - ChartType::MessageWeekDay, - ChartType::MessageWeekDay.to_string(), - ).on_hover_text("Chart showing the total count of messages each day of the week."); - ui.separator(); - ui.selectable_value( - &mut self.chart().chart_type, - ChartType::ActiveUserWeekDay, - ChartType::ActiveUserWeekDay.to_string(), - ).on_hover_text("Chart displaying the total count of active users for each day of the week."); - ui.separator(); - if ui.button("Customize View").clicked() { - self.chart().modal_open = true; + if let Some(chart_type) = + Tabs::new("chart_type", ChartType::iter(), &self.chart_i().chart_type) + .style(TabStyle::Segmented) + .min_item_width(90.0) + .hover_text(|chart_type| chart_type.hover_text().to_string()) + .show(ui) + { + self.chart().chart_type = chart_type; } + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if ui.button("Customize View").clicked() { + self.chart().modal_open = true; + } + }); }); - if not_weekday_chart { - ui.separator(); - ui.horizontal(|ui| { - ui.selectable_value( - &mut self.chart().chart_timing, - ChartTiming::Hourly, - ChartTiming::Hourly.to_string(), - ); - ui.separator(); - ui.selectable_value( - &mut self.chart().chart_timing, - ChartTiming::Daily, - ChartTiming::Daily.to_string(), - ); - ui.separator(); - ui.selectable_value( - &mut self.chart().chart_timing, - ChartTiming::Weekly, - ChartTiming::Weekly.to_string(), - ); - ui.separator(); - ui.selectable_value( - &mut self.chart().chart_timing, - ChartTiming::Monthly, - "Monthly", - ); + + ui.add_space(4.0); + ui.horizontal(|ui| { + if not_weekday_chart + && let Some(timing) = Tabs::new( + "chart_timing", + ChartTiming::iter(), + &self.chart_i().chart_timing, + ) + .style(TabStyle::Segmented) + .equal_width(true) + .min_item_width(70.0) + .hover_text(|timing| { + format!("Group the data by {}", timing.to_string().to_lowercase()) + }) + .show(ui) + { + self.chart().chart_timing = timing; + } + + // Quick switches for the two summary series, no need to dig through the user list + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let mut whitelisted = self.chart_i().added_to_chart.contains(WHITELISTED_DATA); + if ui + .checkbox(&mut whitelisted, "Whitelisted") + .on_hover_text("Show the combined data of all whitelisted users") + .changed() + { + self.chart() + .set_summary_series(WHITELISTED_DATA, whitelisted); + } + + let mut total = self.chart_i().added_to_chart.contains(TOTAL_DATA); + if ui + .checkbox(&mut total, "Total") + .on_hover_text("Show the combined data of every user") + .changed() + { + self.chart().set_summary_series(TOTAL_DATA, total); + } }); - ui.separator(); - } else { - ui.separator(); - } + }); + + ui.add_space(4.0); + ui.separator(); if self.chart().modal_open { self.chart().show_modal_popup(ui); @@ -458,76 +489,65 @@ impl MainWindow { if not_weekday_chart { let date_enabled = !self.is_processing && !self.chart().available_users.is_empty(); - ui.add_enabled_ui(date_enabled, |ui| { - ui.horizontal(|ui| { - let chart = self.chart(); - - ui.label("From:"); - ui.add( - DatePickerButton::new(chart.date_nav.handler().from()) - .id_salt("1"), - ) - .on_hover_text("Show data only after this date, including the date itself"); - ui.label("To:"); - - ui.add( - DatePickerButton::new(chart.date_nav.handler().to()).id_salt("2"), - ) - .on_hover_text("Show data only before this date, incluyding the date itself"); - - let reset_button = ui.button("Reset Date Selection").on_hover_text("Reset selected date to the oldest and the newest date with at least 1 data point"); - if reset_button.clicked() { - chart.date_nav.handler().reset_dates(); - chart.reset_saved_bars(); - } + Card::new().show(ui, |ui| { + ui.add_enabled_ui(date_enabled, |ui| { + ui.horizontal(|ui| { + let chart = self.chart(); + + ui.label("From:"); + ui.add( + DatePickerButton::new(chart.date_nav.handler().from()) + .id_salt("1"), + ) + .on_hover_text("Show data only after this date, including the date itself"); + ui.label("To:"); + + ui.add( + DatePickerButton::new(chart.date_nav.handler().to()).id_salt("2"), + ) + .on_hover_text("Show data only before this date, incluyding the date itself"); + + let reset_button = ui.button("Reset Date Selection").on_hover_text("Reset selected date to the oldest and the newest date with at least 1 data point"); + if reset_button.clicked() { + chart.date_nav.handler().reset_dates(); + chart.reset_saved_bars(); + } - ui.separator(); - - let hover_position = ui.make_persistent_id("nav_hovered_2"); - let selected_position = ui.make_persistent_id("nav_selected_2"); - for nav in NavigationType::iter() { - let selected = chart.date_nav.nav_type_i() == nav; - let resp = ui.add(AnimatedLabel::new( - selected, - nav.to_string(), - selected_position, - hover_position, - 50.0, - 20.0, - None, - (false, false), - )); - - if resp.clicked() { + if let Some(nav) = Tabs::new("nav_type_2", NavigationType::iter(), &chart.date_nav.nav_type_i()) + .style(TabStyle::Segmented) + .min_item_width(50.0) + .equal_width(true) + .show(ui) + { *chart.date_nav.nav_type() = nav; } - } - - ui.separator(); - let previous_hover = format!("Go back by 1 {} from the current date. Shortcut Key: CTRL + H", chart.date_nav.nav_name()); - let next_hover = format!("Go next by 1 {} from the current date. Shortcut Key: CTRL + L", chart.date_nav.nav_name()); + let previous_hover = format!("Go back by 1 {} from the current date. Shortcut Key: CTRL + H", chart.date_nav.nav_name()); + let next_hover = format!("Go next by 1 {} from the current date. Shortcut Key: CTRL + L", chart.date_nav.nav_name()); - if ui.button(format!("Previous {}", chart.date_nav.nav_name())).on_hover_text(previous_hover).clicked() { - chart.date_nav.go_previous(); - } + if ui.button(format!("Previous {}", chart.date_nav.nav_name())).on_hover_text(previous_hover).clicked() { + chart.date_nav.go_previous(); + } - if ui.button(format!("Next {}", chart.date_nav.nav_name())).on_hover_text(next_hover).clicked() { - chart.date_nav.go_next(); - } + if ui.button(format!("Next {}", chart.date_nav.nav_name())).on_hover_text(next_hover).clicked() { + chart.date_nav.go_next(); + } + }); }); }); + ui.add_space(4.0); + // Monitor for H and L key presses if date_enabled { let is_ctrl_pressed = ui.ctx().input(|i| i.modifiers.ctrl); let key_h_pressed = ui.ctx().input(|i| i.key_pressed(Key::H)); + let key_l_pressed = ui.ctx().input(|i| i.key_pressed(Key::L)); - if key_h_pressed && is_ctrl_pressed { - self.chart().date_nav.go_previous(); - } else { - let key_l_pressed = ui.ctx().input(|i| i.key_pressed(Key::L)); - if key_l_pressed && is_ctrl_pressed { + if is_ctrl_pressed { + if key_h_pressed { + self.chart().date_nav.go_previous(); + } else if key_l_pressed { self.chart().date_nav.go_next(); } } @@ -633,7 +653,7 @@ impl MainWindow { // In case a common time does not include a user that is added in the chart // add a 0 value bar for i in &self.chart_i().added_to_chart { - if !user.contains_key(i) && i != "Show total data" && i != "Show whitelisted data" { + if !user.contains_key(i) && i != TOTAL_DATA && i != WHITELISTED_DATA { let bar = Bar::new(arg, 0.0).name(format!( "{} {i}", time_to_string(key, self.chart_i().chart_timing) @@ -649,7 +669,7 @@ impl MainWindow { if show_whitelisted_message { let is_whitelisted = self .whitelist - .is_user_whitelisted(*self.chart_i().user_ids.get(user_name).unwrap()); + .contains(*self.chart_i().user_ids.get(user_name).unwrap()); if is_whitelisted { whitelisted_message += num; @@ -677,9 +697,7 @@ impl MainWindow { "{} Total message", time_to_string(key, self.chart_i().chart_timing) )); - let bar_value = bar_list - .entry("Show total data".to_owned()) - .or_insert(Vec::new()); + let bar_value = bar_list.entry(TOTAL_DATA.to_owned()).or_insert(Vec::new()); bar_value.push(bar); } @@ -689,10 +707,11 @@ impl MainWindow { time_to_string(key, self.chart_i().chart_timing) )); let bar_value = bar_list - .entry("Show whitelisted data".to_owned()) + .entry(WHITELISTED_DATA.to_owned()) .or_insert(Vec::new()); bar_value.push(bar); } + point_dates.insert(index as i64, (*key, total_message, whitelisted_message)); } @@ -776,7 +795,7 @@ impl MainWindow { for user_name in user.keys() { let is_whitelisted = self .whitelist - .is_user_whitelisted(*self.chart_i().user_ids.get(user_name).unwrap()); + .contains(*self.chart_i().user_ids.get(user_name).unwrap()); if is_whitelisted { whitelisted_user += 1; @@ -792,9 +811,7 @@ impl MainWindow { "{} Total user", time_to_string(key, self.chart_i().chart_timing) )); - let bar_value = bar_list - .entry("Show total data".to_owned()) - .or_insert(Vec::new()); + let bar_value = bar_list.entry(TOTAL_DATA.to_owned()).or_insert(Vec::new()); bar_value.push(bar); } @@ -804,7 +821,7 @@ impl MainWindow { time_to_string(key, self.chart_i().chart_timing) )); let bar_value = bar_list - .entry("Show whitelisted data".to_owned()) + .entry(WHITELISTED_DATA.to_owned()) .or_insert(Vec::new()); bar_value.push(bar); } @@ -850,7 +867,7 @@ impl MainWindow { if show_whitelisted_message { let is_whitelisted = self .whitelist - .is_user_whitelisted(*self.chart_i().user_ids.get(user_name).unwrap()); + .contains(*self.chart_i().user_ids.get(user_name).unwrap()); if is_whitelisted { whitelisted_message += num; @@ -865,9 +882,7 @@ impl MainWindow { if show_total_message { let bar = Bar::new(arg, total_message as f64) .name(format!("{} Total message", weekday_num_to_string(*key))); - let bar_value = bar_list - .entry("Show total data".to_owned()) - .or_insert(Vec::new()); + let bar_value = bar_list.entry(TOTAL_DATA.to_owned()).or_insert(Vec::new()); bar_value.push(bar); } @@ -877,13 +892,13 @@ impl MainWindow { weekday_num_to_string(*key) )); let bar_value = bar_list - .entry("Show whitelisted data".to_owned()) + .entry(WHITELISTED_DATA.to_owned()) .or_insert(Vec::new()); bar_value.push(bar); } point_dates.insert( index as i64, - (NaiveDateTime::default(), total_message, whitelisted_message), + (DateTime::default(), total_message, whitelisted_message), ); } @@ -912,7 +927,7 @@ impl MainWindow { for user_name in user.keys() { let is_whitelisted = self .whitelist - .is_user_whitelisted(*self.chart_i().user_ids.get(user_name).unwrap()); + .contains(*self.chart_i().user_ids.get(user_name).unwrap()); if is_whitelisted { whitelisted_user += 1; @@ -926,9 +941,7 @@ impl MainWindow { if show_total_message { let bar = Bar::new(arg, total_user as f64) .name(format!("{} Total user", weekday_num_to_string(*key))); - let bar_value = bar_list - .entry("Show total data".to_owned()) - .or_insert(Vec::new()); + let bar_value = bar_list.entry(TOTAL_DATA.to_owned()).or_insert(Vec::new()); bar_value.push(bar); } @@ -936,14 +949,14 @@ impl MainWindow { let bar = Bar::new(arg, f64::from(whitelisted_user)) .name(format!("{} Whitelisted user", weekday_num_to_string(*key))); let bar_value = bar_list - .entry("Show whitelisted data".to_owned()) + .entry(WHITELISTED_DATA.to_owned()) .or_insert(Vec::new()); bar_value.push(bar); } point_dates.insert( index as i64, ( - NaiveDateTime::default(), + DateTime::default(), total_user as u64, whitelisted_user as u64, ), @@ -977,13 +990,12 @@ impl MainWindow { // In case the date picker is used the bar list may not contain the following bar names // even if they are already in the list if show_whitelisted_message { - if let Some(whitelist_bar) = bar_list.remove("Show whitelisted data") { + if let Some(whitelist_bar) = bar_list.remove(WHITELISTED_DATA) { let mut whitelist_chart = BarChart::new("Whitelist", whitelist_bar) .width(1.0) .name(whitelist_data_name); - if show_total_message - && let Some(total_message_bars) = bar_list.remove("Show total data") + if show_total_message && let Some(total_message_bars) = bar_list.remove(TOTAL_DATA) { let total_message_chart = BarChart::new("Total message", total_message_bars) .width(1.0) @@ -992,14 +1004,14 @@ impl MainWindow { whitelist_chart = whitelist_chart.stack_on(&[&total_message_chart]); all_charts.push(total_message_chart); } + all_charts.push(whitelist_chart); } - } else if show_total_message - && let Some(total_message_bars) = bar_list.remove("Show total data") - { + } else if show_total_message && let Some(total_message_bars) = bar_list.remove(TOTAL_DATA) { let total_message_chart = BarChart::new("Total message", total_message_bars) .width(1.0) .name(total_data_name); + all_charts.push(total_message_chart); } @@ -1062,15 +1074,23 @@ impl MainWindow { match chart_type { ChartType::Message | ChartType::ActiveUser => match timing { ChartTiming::Hourly | ChartTiming::Daily => { - date_label = date.to_string(); + date_label = format_datetime(date); } ChartTiming::Weekly => { - let other_date = date.checked_add_days(Days::new(7)).unwrap(); - date_label = format!("{date} - {other_date}"); + let other_date = date.checked_add(7.days()).unwrap(); + date_label = format!( + "{} - {}", + format_datetime(date), + format_datetime(&other_date) + ); } ChartTiming::Monthly => { - let other_date = date.checked_add_months(Months::new(1)).unwrap(); - date_label = format!("{date} - {other_date}"); + let other_date = date.checked_add(1.month()).unwrap(); + date_label = format!( + "{} - {}", + format_datetime(date), + format_datetime(&other_date) + ); } }, ChartType::MessageWeekDay | ChartType::ActiveUserWeekDay => { diff --git a/src/ui/tabs/mod.rs b/src/ui/tabs/mod.rs new file mode 100644 index 0000000..361ca35 --- /dev/null +++ b/src/ui/tabs/mod.rs @@ -0,0 +1,11 @@ +mod accounts; +mod charts; +mod scan; +mod user_list; +mod users; + +pub use accounts::*; +pub use charts::*; +pub use scan::*; +pub use user_list::*; +pub use users::*; diff --git a/src/ui_components/tab_ui/counter.rs b/src/ui/tabs/scan.rs similarity index 77% rename from src/ui_components/tab_ui/counter.rs rename to src/ui/tabs/scan.rs index afc07fa..54407e7 100644 --- a/src/ui_components/tab_ui/counter.rs +++ b/src/ui/tabs/scan.rs @@ -1,20 +1,21 @@ use eframe::egui::{ - Align, Button, ComboBox, Grid, Label, Layout, ProgressBar, TextEdit, Ui, ViewportCommand, vec2, + Align, Button, ComboBox, Grid, Label, Layout, ProgressBar, RichText, TextEdit, Ui, + ViewportCommand, vec2, }; use log::info; use std::collections::HashMap; -use std::sync::atomic::Ordering; -use crate::tg_handler::ProcessStart; -use crate::ui_components::MainWindow; -use crate::ui_components::processor::{CounterCounts, ParsedChat, ProcessState}; -use crate::utils::{chat_to_text, parse_chat_details}; +use crate::telegram::Command; +use crate::ui::MainWindow; +use crate::ui::state::{CounterCounts, ParsedChat, ProcessState}; +use crate::ui::widgets::{Card, PrimaryButton, StatTile}; +use crate::utils::{chat_to_text, find_session_files, parse_chat_details}; const LIMIT_SELECTION: [&str; 5] = ["30", "40", "50", "80", "100"]; #[derive(Clone)] pub struct CounterData { - session_index: usize, + pub session_index: usize, start_from: String, end_at: String, pub counts: Vec, @@ -60,6 +61,7 @@ impl CounterData { self.ongoing_chat = 0; self.session_percentage = HashMap::new(); } + pub fn ongoing_chat(&self) -> usize { self.ongoing_chat } @@ -158,6 +160,10 @@ impl CounterData { } } + pub fn bar_percentage(&self) -> f32 { + self.bar_percentage + } + pub fn counting(&self) -> bool { self.counting } @@ -203,88 +209,74 @@ impl CounterData { impl MainWindow { pub fn show_counter_ui(&mut self, ui: &mut Ui) { - Grid::new("Counter Grid") - .num_columns(2) - .spacing([5.0, 10.0]) - .show(ui, |ui| self.show_grid_data(ui)); - - ui.add_space(10.0); - ui.label(self.counter.detected_chat.clone()); - ui.add_space(5.0); - ui.horizontal(|ui| { - Grid::new("Main") + Card::new().show(ui, |ui| { + Grid::new("Counter Grid") .num_columns(2) - .spacing([5.0, 10.0]) - .show(ui, |ui| { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.label("Messages Checked:") - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - ui.label(format!("{}", self.count().total_message)); - }); - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.label("Whitelisted Messages:") - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - ui.label(format!("{}", self.count().whitelisted_message)); - }); - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.label("Users Found:") - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - ui.label(format!("{}", self.count().total_user)); - }); - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.label("Whitelisted Users:") - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - ui.label(format!("{}", self.count().total_whitelisted())); - }); - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.label("Deleted Message:") - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - ui.label(format!("{}", self.count().deleted_message)); - }); - - ui.end_row(); - }); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add_space(80.0); - - if self.is_processing && self.counter.counting() { - let cancel_button = ui.add_sized([80.0, 40.0], Button::new("Cancel")); - if cancel_button.clicked() { - self.cancel_count(); - } - } else if self.is_processing { - ui.add_enabled(false, Button::new("Start").min_size(vec2(80.0, 40.0))); - } else { - let start_button = ui.add_sized([80.0, 40.0], Button::new("Start")); - if start_button.clicked() { - self.start_counting(); - } - } - }); + .spacing([8.0, 10.0]) + .show(ui, |ui| self.show_grid_data(ui)); + }); + + ui.add_space(6.0); + ui.label(RichText::new(self.counter.detected_chat.clone()).weak()); + ui.add_space(8.0); + + let stats = [ + ( + "Messages", + "Total messages checked", + self.count().total_message, + ), + ( + "Whitelisted Msgs", + "Messages sent by whitelisted users", + self.count().whitelisted_message, + ), + ("Users", "Total users found", self.count().total_user), + ( + "Whitelisted Users", + "Total whitelisted users found", + self.count().total_whitelisted() as i32, + ), + ( + "Deleted Msgs", + "Deleted messages", + self.count().deleted_message, + ), + ]; + + let spacing = ui.spacing().item_spacing.x; + let tile_width = + (ui.available_width() - spacing * (stats.len() - 1) as f32) / stats.len() as f32; + + ui.horizontal(|ui| { + for (label, hover, value) in stats { + ui.add(StatTile::new(label, value, tile_width)) + .on_hover_text(hover); + } }); + // Laid out from the bottom: progress bar last, the main button right above it ui.with_layout(Layout::bottom_up(Align::Min), |ui| { let progress_bar = ProgressBar::new(self.counter.bar_percentage) .show_percentage() .animate(self.counter.counting); ui.add(progress_bar); + ui.add_space(8.0); + + let size = vec2(ui.available_width(), 38.0); + + if self.is_processing && self.counter.counting() { + if ui + .add(PrimaryButton::new("Cancel").size(size).danger(true)) + .clicked() + { + self.cancel_count(); + } + } else if self.is_processing { + ui.add_enabled(false, PrimaryButton::new("Start").size(size)); + } else if ui.add(PrimaryButton::new("Start").size(size)).clicked() { + self.start_counting(); + } }); self.counter.detected_chat = @@ -334,13 +326,22 @@ impl MainWindow { ComboBox::from_id_salt("Session Box").show_index( ui, &mut self.counter.session_index, - self.tg_clients.len(), + self.backend.session_count(), |i| &values[i], ); + if ui + .add_enabled(!self.is_processing, Button::new("Reload")) + .on_hover_text( + "Remove sessions that got logged out and connect saved sessions that are not connected yet", + ) + .clicked() + { + self.reload_sessions(); + } ui.checkbox(&mut self.counter.use_all_sessions, "Use all sessions") .on_hover_text( "Whether to use all the available sessions for counting - + Automatically divides the tasks among sessions, dramatically increasing speed. How to get more sessions? @@ -368,11 +369,13 @@ visible in the UI. Info: Each session can count about 3000 messages before flood wait is triggered.", ); }); + ui.end_row(); ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.add(Label::new("Starting Point:")); }); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { let clear_paste_button = if self.counter.start_from.is_empty() { ui.add(Button::new("Paste")) @@ -404,6 +407,7 @@ If message number is not specified, starts from the latest message. Starting message number will always be bigger than the ending message. To count all messages in a chat, paste the latest message link.", ); + if clear_paste_button.clicked() { if self.counter.start_from.is_empty() { target_textbox.request_focus(); @@ -415,6 +419,7 @@ To count all messages in a chat, paste the latest message link.", }); ui.end_row(); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { ui.add(Label::new("Ending Point:")); }); @@ -450,6 +455,7 @@ If message number is not specified or is empty, counts all messages. Ending message number will always be smaller than the starting message. To count all messages in a chat, paste the very first message link or keep it empty.", ); + if clear_paste_button.clicked() { if self.counter.end_at.is_empty() { target_textbox.request_focus(); @@ -493,6 +499,7 @@ To count all messages in a chat, paste the very first message link or keep it em self.reset_table(); self.reset_chart(); } + self.initial_chart_reset(); self.append_structs(total_parsed, self.counter.total_chats()); self.process_next_count(); @@ -525,32 +532,44 @@ To count all messages in a chat, paste the very first message link or keep it em let start_num = chat.start_point(); let end_num = chat.end_point(); - let client = self.tg_clients.get(&selected_client).unwrap().clone(); + self.backend.reset_cancel(); - if self.counter.use_all_sessions && self.tg_clients.len() > 1 { - self.runtime.spawn(async move { - client - .start_process(ProcessStart::CheckChatExistence( - chat_name, start_num, end_num, - )) - .await; + if self.counter.use_all_sessions && self.backend.session_count() > 1 { + self.backend.send(Command::CheckChat { + session: selected_client, + chat: chat_name, + start: start_num, + end: end_num, }); } else { - let cancel = self.cancel_count.clone(); - self.runtime.spawn(async move { - client - .start_process(ProcessStart::StartCount( - chat_name, start_num, end_num, false, cancel, - )) - .await; + self.backend.send(Command::StartCount { + session: selected_client, + chat: chat_name, + start: start_num, + end: end_num, + multi_session: false, }); } } + /// Checks the connected sessions and connects saved ones that are missing + fn reload_sessions(&mut self) { + let connected = self.get_session_names(); + let new_files: Vec = find_session_files() + .into_iter() + .filter(|file| !connected.contains(&file.replace(".sqlite", ""))) + .collect(); + + self.is_processing = true; + self.process_state = ProcessState::ConnectingSessions; + self.backend.send(Command::RefreshSessions { new_files }); + } + /// Returns the session name that is selected on the combo box pub fn get_selected_session(&self) -> String { let all_sessions = self.get_session_names(); let selected_index = self.counter.session_index; + if let Some(session) = all_sessions.get(selected_index) { session.to_owned() } else { @@ -559,6 +578,6 @@ To count all messages in a chat, paste the very first message link or keep it em } fn cancel_count(&mut self) { - self.cancel_count.store(true, Ordering::Release); + self.backend.cancel_scan(); } } diff --git a/src/ui/tabs/user_list.rs b/src/ui/tabs/user_list.rs new file mode 100644 index 0000000..245a1d0 --- /dev/null +++ b/src/ui/tabs/user_list.rs @@ -0,0 +1,486 @@ +use eframe::egui::scroll_area::DragScroll; +use eframe::egui::{ + Align, Align2, Button, Color32, Label, Layout, Response, RichText, Sense, TextEdit, Ui, vec2, +}; +use egui_extras::Column; +use egui_selectable_table::{ + ColumnOperations, ColumnOrdering, SelectableRow, SelectableTable, SortOrder, +}; +use grammers_session::types::PeerRef; +use log::{error, info}; +use std::collections::HashSet; + +use crate::telegram::Command; +use crate::ui::MainWindow; +use crate::ui::state::{ColumnName, ListKind, PackedUser, ProcessState}; +use crate::ui::widgets::{Card, PrimaryButton, RowLabel}; +use crate::utils::{get_saved_users, save_users, separate_by_seen}; + +#[derive(Default)] +struct Config { + deleted_selected: bool, +} + +impl ColumnOperations for ColumnName { + fn column_text(&self, row: &ListRowData) -> String { + match self { + ColumnName::Name => row.name.clone(), + ColumnName::Username => row.username.clone(), + ColumnName::UserID => row.id.to_string(), + _ => unreachable!(), + } + } + + fn create_header( + &self, + ui: &mut Ui, + _sort_order: Option, + _table: &mut SelectableTable, + ) -> Option { + let label_text = self.to_string(); + let hover_text = match self { + ColumnName::Name => "Telegram name of the user".to_string(), + ColumnName::Username => "Telegram username of the user".to_string(), + + ColumnName::UserID => "Telegram User ID of the user".to_string(), + _ => unreachable!(), + }; + + let label_text = RichText::new(label_text).strong(); + + let response = ui + .add_sized(ui.available_size(), Label::new(label_text)) + .on_hover_text(hover_text); + + Some(response) + } + + fn create_table_row( + &self, + ui: &mut Ui, + row: &SelectableRow, + column_selected: bool, + table: &mut SelectableTable, + ) -> Response { + let row_data = &row.row_data; + let mut show_tooltip = false; + + let row_text = match self { + ColumnName::Name => { + show_tooltip = true; + row_data.name.clone() + } + ColumnName::Username => { + show_tooltip = true; + row_data.username.clone() + } + ColumnName::UserID => row_data.id.to_string(), + _ => unreachable!(), + }; + + let is_selected = column_selected; + + let mut label = ui + .add_sized( + ui.available_size(), + RowLabel::new(is_selected, false, &row_text), + ) + .interact(Sense::drag()); + + if show_tooltip { + label = label.on_hover_text(row_text); + } + + label.context_menu(|ui| { + if ui.button("Deleted Selected").clicked() { + table.config.deleted_selected = true; + ui.close(); + } + }); + + label + } +} + +impl ColumnOrdering for ColumnName { + fn order_by(&self, row_1: &ListRowData, row_2: &ListRowData) -> std::cmp::Ordering { + row_1.name.cmp(&row_2.name) + } +} + +#[derive(Clone)] +struct ListRowData { + name: String, + username: String, + id: i64, + belongs_to: PeerRef, + seen_by: String, +} + +impl ListRowData { + fn new(name: String, username: String, id: i64, belongs_to: PeerRef, seen_by: String) -> Self { + ListRowData { + name, + username, + id, + belongs_to, + seen_by, + } + } +} + +pub struct UserListData { + kind: ListKind, + table: SelectableTable, + target_username: String, + failed: i32, + all_ids: HashSet, + search_query: String, +} + +impl UserListData { + pub fn new(kind: ListKind) -> Self { + let table = SelectableTable::new(vec![ + ColumnName::Name, + ColumnName::Username, + ColumnName::UserID, + ]) + .auto_scroll() + .select_full_row() + .serial_column() + .no_ctrl_a_capture() + .auto_reload(1); + + Self { + kind, + table, + target_username: String::new(), + failed: 0, + all_ids: HashSet::new(), + search_query: String::new(), + } + } +} + +impl UserListData { + /// Add a new row to the UI + pub fn add_user( + &mut self, + name: String, + username: String, + id: i64, + belongs_to: PeerRef, + seen_by: String, + ) { + let name = if name.is_empty() { + String::from("Deleted Account") + } else { + name + }; + + info!("Adding {name} to {}, seen by {seen_by}", self.kind.name()); + self.all_ids.insert(id); + self.table.add_modify_row(|_rows| { + let to_add = ListRowData::new(name, username, id, belongs_to, seen_by); + Some(to_add) + }); + } + + /// Check if the user is in the list + pub fn contains(&self, id: i64) -> bool { + self.all_ids.contains(&id) + } + + /// Save the current row data in the list json + pub fn save(&self, overwrite: bool) { + let packed_chats = self + .table + .get_all_rows() + .values() + .filter_map(|row| { + PackedUser::new(row.row_data.belongs_to, row.row_data.seen_by.clone()) + }) + .collect(); + + save_users(self.kind, packed_chats, overwrite); + } + + /// Removes selected rows from the list and saves the result + fn remove_selected(&mut self) -> Vec { + let active_rows = self.table.get_selected_rows(); + + let mut row_ids = Vec::new(); + for i in &active_rows { + info!( + "Removing user {} | {} from {}", + i.row_data.username, + i.row_data.id, + self.kind.name() + ); + self.all_ids.remove(&i.row_data.id); + self.table.add_modify_row(|rows| { + rows.remove(&i.id); + row_ids.push(i.row_data.id); + None + }); + } + self.save(true); + row_ids + } + + /// Removes all rows from the list and saves the result + fn remove_all(&mut self) -> Vec { + info!("Removing all users from {}", self.kind.name()); + let row_keys = self.all_ids.iter().copied().collect(); + self.table.clear_all_rows(); + self.save(true); + self.all_ids.clear(); + + row_keys + } + + pub fn clear_text_box(&mut self) { + self.target_username.clear(); + } + + pub fn increase_failed_by(&mut self, count: i32) { + self.failed += count; + } + + pub fn row_len(&self) -> usize { + self.table.total_rows() + } + + pub fn failed_num(&self) -> i32 { + self.failed + } +} + +impl MainWindow { + pub fn list_data(&mut self, kind: ListKind) -> &mut UserListData { + match kind { + ListKind::Whitelist => &mut self.whitelist, + ListKind::Blacklist => &mut self.blacklist, + } + } + + /// Updates everything that depends on the list after users were removed from it + fn on_list_users_removed(&mut self, kind: ListKind, ids: &[i64]) { + // Blacklisted users never had their data hidden, nothing to restore + if kind == ListKind::Whitelist { + self.table().remove_whitelist(ids); + self.chart().reset_saved_bars(); + } + } + + pub fn show_list_ui(&mut self, ui: &mut Ui, kind: ListKind) { + let name = kind.name(); + let adjective = kind.adjective(); + + if self.list_data(kind).table.config.deleted_selected { + self.list_data(kind).table.config.deleted_selected = false; + let deleted = self.list_data(kind).remove_selected(); + + self.on_list_users_removed(kind, &deleted); + self.process_state = ProcessState::ListUsersRemoved(kind, deleted.len()); + } + + Card::new() + .title(format!("ADD TO {}", name.to_uppercase())) + .show(ui, |ui| { + ui.horizontal(|ui| { + let button_size = vec2(80.0, 28.0); + let text_width = + ui.available_width() - button_size.x - ui.spacing().item_spacing.x; + let is_processing = self.is_processing; + let list = self.list_data(kind); + + ui.add_sized( + [text_width, button_size.y], + TextEdit::singleline(&mut list.target_username) + .align(Align2::LEFT_CENTER) + .hint_text("Telegram username: @username"), + ) + .on_hover_text(format!( + "Don't have a username?\n\nUse the Scan tab to count at least 1 message by that user\nthen right click on the Users tab to {name}" + )); + + let can_add = !is_processing && !list.target_username.is_empty(); + let add = ui + .add_enabled(can_add, PrimaryButton::new("Add").size(button_size)) + .on_hover_text(format!("Add the username to {name}")); + + if add.clicked() { + self.add_list_user(kind); + } + }); + }); + + ui.add_space(8.0); + + let list = self.list_data(kind); + let failed = list.failed_num(); + let mut summary = format!("{} users", list.row_len()); + if failed > 0 { + summary.push_str(&format!(" ({failed} failed to load)")); + } + ui.label(RichText::new(summary).weak()); + ui.add_space(4.0); + + let column_size = (ui.available_width() - 20.0) / 3.0; + + ui.horizontal(|ui| { + let list = self.list_data(kind); + let text_box = TextEdit::singleline(&mut list.search_query) + .hint_text("Search by name, username or user ID"); + ui.add(text_box); + + if ui + .button("Search") + .on_hover_text("Filter rows that match the search query") + .clicked() + { + let search_query = list.search_query.clone(); + + if search_query.is_empty() { + list.table.recreate_rows(); + } else { + let column_list = vec![ColumnName::Name, ColumnName::Username, ColumnName::UserID]; + + list.table + .search_and_show(&column_list, &search_query, None, None); + } + } + if ui + .button("Clear") + .on_hover_text("Clear search result") + .clicked() + { + list.table.recreate_rows(); + list.search_query.clear(); + } + + ui.separator(); + + if ui + .button("Select All") + .on_hover_text("Select all users. Also usable with CTRL + A. Use CTRL + mouse click for manual selection") + .clicked() + { + list.table.select_all(); + } + if ui + .button("Delete Selected") + .on_hover_text(format!("Delete selected users from {name}")) + .clicked() + { + let deleted = list.remove_selected(); + + self.on_list_users_removed(kind, &deleted); + self.process_state = ProcessState::ListUsersRemoved(kind, deleted.len()); + } + if ui + .add(Button::new( + RichText::new("Delete All").color(Color32::from_rgb(220, 90, 90)), + )) + .on_hover_text(format!("Delete all {adjective} users")) + .clicked() + { + let deleted = self.list_data(kind).remove_all(); + + self.on_list_users_removed(kind, &deleted); + self.process_state = ProcessState::ListCleared(kind); + } + }); + + ui.separator(); + + self.list_data(kind).table.show_ui(ui, |table| { + table + .striped(true) + .cell_layout(Layout::left_to_right(Align::Center)) + .column(Column::exact(column_size).clip(true)) + .column(Column::exact(column_size)) + .column(Column::exact(column_size)) + .drag_to_scroll(DragScroll::Never) + .auto_shrink([false; 2]) + .min_scrolled_height(0.0) + }); + } + + /// Loads the saved users of a list and asks the sessions that saw them to resolve them + pub fn load_saved_list(&mut self, kind: ListKind) { + // This function will never be called if there are no sessions detected. + // Unnecessary to handle in case is empty + + let saved_users = match get_saved_users(kind) { + Ok(users) => users, + Err(_) => { + // This case means it failed to deserialize the json or is using the old json format + // All previous data will be removed + error!( + "Failed to deserialize the {} json file. Deleting saved json data", + kind.name() + ); + self.list_data(kind).save(true); + self.process_state = ProcessState::ListLoadFailed(kind); + self.is_processing = false; + return; + } + }; + + // separate the saved data by seen_by as the key and the peer refs as the value + let separated_data = separate_by_seen(kind, saved_users); + + if separated_data.is_empty() { + self.is_processing = false; + return; + } + + // Ask each unique session found in the json to resolve its own peer refs + // `peer_refs` cannot be empty as the key will only exist if there is at least one peer ref found + for (seen_by, peer_refs) in separated_data { + if !self.backend.has_session(&seen_by) { + let total = peer_refs.len(); + error!( + "{seen_by} client does not exist! Ignoring {total} {} users", + kind.adjective() + ); + let list = self.list_data(kind); + list.increase_failed_by(total as i32); + + let (loaded, failed) = (list.row_len(), list.failed_num()); + self.process_state = ProcessState::ListLoaded(kind, loaded, failed); + continue; + } + + self.backend.send(Command::LoadList { + kind, + session: seen_by, + peers: peer_refs, + }); + } + } + + pub fn add_list_user(&mut self, kind: ListKind) { + let selected_session = self.get_selected_session(); + + if selected_session.is_empty() { + self.process_state = ProcessState::EmptySelectedSession; + return; + } + + let username = self + .list_data(kind) + .target_username + .clone() + .replace('@', ""); + self.is_processing = true; + + self.backend.send(Command::AddListUser { + kind, + session: selected_session, + username, + }); + } +} diff --git a/src/ui_components/tab_ui/user_table.rs b/src/ui/tabs/users.rs similarity index 73% rename from src/ui_components/tab_ui/user_table.rs rename to src/ui/tabs/users.rs index 00cb2b8..0edb7f7 100644 --- a/src/ui_components/tab_ui/user_table.rs +++ b/src/ui/tabs/users.rs @@ -1,24 +1,24 @@ -use chrono::{NaiveDate, NaiveDateTime}; use eframe::egui::scroll_area::DragScroll; use eframe::egui::{Align, Button, ComboBox, Key, Layout, Response, RichText, Sense, TextEdit, Ui}; use egui_extras::{Column, DatePickerButton}; use egui_selectable_table::{ ColumnOperations, ColumnOrdering, SelectableRow, SelectableTable, SortOrder, }; -use grammers_client::types::{Chat, Message}; +use grammers_client::message::Message; +use grammers_client::peer::Peer; +use grammers_session::types::PeerRef; +use jiff::civil::{Date, DateTime}; use log::info; use serde::Serialize; use std::collections::{HashMap, HashSet}; use std::env::current_dir; use strum::IntoEnumIterator; -use crate::ui_components::MainWindow; -use crate::ui_components::processor::{ - ColumnName, DateNavigator, NavigationType, PackedBlacklistedUser, PackedWhitelistedUser, - ProcessState, -}; -use crate::ui_components::widgets::{AnimatedLabel, RowLabel}; -use crate::utils::{entry_insert_user, export_table_data, to_chart_name}; +use crate::ui::MainWindow; +use crate::ui::dates::DateNavigator; +use crate::ui::state::{ColumnName, ListKind, NavigationType, ProcessState, peer_details}; +use crate::ui::widgets::{Card, RowLabel, StatTile, TabStyle, Tabs}; +use crate::utils::{entry_insert_user, export_table_data, format_datetime, to_chart_name}; #[derive(Default)] pub struct Config { @@ -38,11 +38,11 @@ pub struct UserRowData { total_char: u32, average_word: u32, average_char: u32, - first_seen: NaiveDateTime, - last_seen: NaiveDateTime, + first_seen: DateTime, + last_seen: DateTime, whitelisted: bool, #[serde(skip_serializing)] - belongs_to: Option, + belongs_to: Option, #[serde(skip_serializing)] seen_by: String, } @@ -58,8 +58,8 @@ impl ColumnOperations for ColumnName { ColumnName::TotalChar => row.total_char.to_string(), ColumnName::AverageWord => row.average_word.to_string(), ColumnName::AverageChar => row.average_char.to_string(), - ColumnName::FirstMessageSeen => row.first_seen.to_string(), - ColumnName::LastMessageSeen => row.last_seen.to_string(), + ColumnName::FirstMessageSeen => format_datetime(&row.first_seen), + ColumnName::LastMessageSeen => format_datetime(&row.last_seen), ColumnName::Whitelisted => row.whitelisted.to_string(), } } @@ -151,13 +151,14 @@ impl ColumnOperations for ColumnName { ColumnName::TotalChar => row_data.total_char.to_string(), ColumnName::AverageWord => row_data.average_word.to_string(), ColumnName::AverageChar => row_data.average_char.to_string(), - ColumnName::FirstMessageSeen => row_data.first_seen.to_string(), - ColumnName::LastMessageSeen => row_data.last_seen.to_string(), + ColumnName::FirstMessageSeen => format_datetime(&row_data.first_seen), + ColumnName::LastMessageSeen => format_datetime(&row_data.last_seen), ColumnName::Whitelisted => { let text = if row_data.whitelisted { "Yes" } else { "No" }; text.to_string() } }; + let is_selected = column_selected; let is_whitelisted = row_data.whitelisted; @@ -171,6 +172,7 @@ impl ColumnOperations for ColumnName { if show_tooltip { label = label.on_hover_text(row_text); } + label.context_menu(|ui| { if ui.button("Copy selected rows").clicked() { table.config.copy_selected = true; @@ -190,6 +192,7 @@ impl ColumnOperations for ColumnName { ui.close(); } }); + label } } @@ -218,8 +221,8 @@ impl UserRowData { username: &str, id: i64, whitelisted: bool, - belongs_to: Option, - date: NaiveDateTime, + belongs_to: Option, + date: DateTime, seen_by: String, ) -> Self { let username = username.to_string(); @@ -264,12 +267,12 @@ impl UserRowData { } /// Update the date this user was first seen in the chat - fn set_first_seen(&mut self, date: NaiveDateTime) { + fn set_first_seen(&mut self, date: DateTime) { self.first_seen = date; } /// Update the date this user was last seen in the chat - fn set_last_seen(&mut self, date: NaiveDateTime) { + fn set_last_seen(&mut self, date: DateTime) { self.last_seen = date; } } @@ -278,7 +281,8 @@ pub struct UserTableData { /// Key: The Date where at least one message/User was found /// Value: A hashmap of the founded User with their user id as the key /// Contains all data points and UI points are recreated from here - user_data: HashMap>, + user_data: HashMap>, + blacklisted_messages: HashMap, table: SelectableTable, date_nav: DateNavigator, total_whitelisted_user: u32, @@ -298,6 +302,7 @@ impl Default for UserTableData { Self { user_data: HashMap::new(), + blacklisted_messages: HashMap::new(), table, date_nav: DateNavigator::default(), total_whitelisted_message: 0, @@ -319,56 +324,29 @@ impl UserTableData { /// Add a user to the table pub fn add_user( &mut self, - sender: Option, - date: NaiveDate, - datetime: NaiveDateTime, + sender: Option<&Peer>, + sender_ref: Option, + date: Date, + datetime: DateTime, seen_by: String, blacklisted: bool, ) -> (i64, String, String) { - let mut user_id = 0; + let user_id; let full_name; let username; - let mut chat = None; - - if let Some(chat_data) = sender { - user_id = chat_data.id(); - chat = Some(chat_data.clone()); - - if let Chat::User(user) = chat_data { - // As per grammers lib doc, empty name can be given if it's a deleted account - full_name = if user.full_name().is_empty() { - "Deleted Account".to_string() - } else { - user.full_name() - }; - - username = if let Some(name) = user.username() { - name.to_string() - } else { - "Empty".to_string() - }; - } else { - full_name = if chat_data.name().is_empty() { - "Deleted Account".to_string() - } else { - chat_data.name().to_string() - }; - username = if let Some(name) = chat_data.username() { - name.to_string() - } else { - "Empty".to_string() - }; - } + if let Some(peer) = sender { + (full_name, username, user_id) = peer_details(peer); } else { - // If there is no Chat value then it could be an anonymous user + // If there is no Peer value then it could be an anonymous user + user_id = 0; full_name = "Anonymous/Unknown".to_string(); username = "Empty".to_string(); } if !blacklisted { let user_row = UserRowData::new( - &full_name, &username, user_id, false, chat, datetime, seen_by, + &full_name, &username, user_id, false, sender_ref, datetime, seen_by, ); entry_insert_user(&mut self.user_data, user_row, user_id, date); @@ -382,8 +360,8 @@ impl UserTableData { &mut self, user_id: i64, message: &Message, - date: NaiveDate, - datetime: NaiveDateTime, + date: Date, + datetime: DateTime, ) { self.reload_count += 1; // If a user sends multiple messages in a day, that specific day data needs to be updated @@ -487,10 +465,27 @@ impl UserTableData { self.create_rows(); } + /// Keep track of a message that was ignored because the sender is blacklisted + pub fn count_blacklisted_message(&mut self, date: Date) { + *self.blacklisted_messages.entry(date).or_default() += 1; + } + + /// Total ignored blacklisted messages within the selected date range + pub fn blacklisted_message_in_range(&self) -> u32 { + self.blacklisted_messages + .iter() + .filter(|(date, _)| self.date_nav.handler_i().within_range(**date)) + .map(|(_, count)| count) + .sum() + } + pub fn remove_blacklisted_rows(&mut self, user_id: &[i64]) { - for row_data in self.user_data.values_mut() { + for (date, row_data) in &mut self.user_data { for id in user_id { - row_data.remove(id); + // Messages that were already counted for this user now count as blacklisted + if let Some(row) = row_data.remove(id) { + *self.blacklisted_messages.entry(*date).or_default() += row.total_message; + } } } self.create_rows(); @@ -531,110 +526,127 @@ impl MainWindow { (names, total_val) } }; - ui.horizontal(|ui| { - ui.label("Selected chat:"); - ComboBox::from_id_salt("Table Box").show_index( - ui, - &mut self.table_chat_index, - len, - |i| &values[i], - ); - ui.separator(); - let button = Button::new("Export Table Data"); - if ui - .add_enabled(date_enabled, button) - .on_hover_text("Export Table data in CSV format") - .clicked() - { - let chat_name = self.counter.selected_chat_name(self.table_chat_index); - self.table().export_data(&chat_name); - self.process_state = - ProcessState::DataExported(current_dir().unwrap().to_string_lossy().into()); - } + + Card::new().show(ui, |ui| { + ui.horizontal(|ui| { + ui.label("Chat:"); + ComboBox::from_id_salt("Table Box").show_index( + ui, + &mut self.table_chat_index, + len, + |i| &values[i], + ); + + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + let button = Button::new("Export to CSV"); + if ui + .add_enabled(date_enabled, button) + .on_hover_text("Export Table data in CSV format") + .clicked() + { + let chat_name = self.counter.selected_chat_name(self.table_chat_index); + self.table().export_data(&chat_name); + self.process_state = ProcessState::DataExported( + current_dir().unwrap().to_string_lossy().into(), + ); + } + }); + }); }); - ui.separator(); + ui.add_space(6.0); + + let stats = [ + ( + "Users", + "Total users in the selected date range", + self.table_i().get_total_user().to_string(), + ), + ( + "Messages", + "Total messages in the selected date range", + self.table_i().total_message.to_string(), + ), + ( + "Whitelisted Users", + "Whitelisted users in the selected date range", + self.table_i().total_whitelisted_user.to_string(), + ), + ( + "Whitelisted Messages", + "Messages by whitelisted users in the selected date range", + self.table_i().total_whitelisted_message.to_string(), + ), + ( + "Blacklisted Messages", + "Messages by blacklisted users in the selected date range. They are ignored and not included in the other numbers", + self.table_i().blacklisted_message_in_range().to_string(), + ), + ]; + + let spacing = ui.spacing().item_spacing.x; + let tile_width = + (ui.available_width() - spacing * (stats.len() - 1) as f32) / stats.len() as f32; ui.horizontal(|ui| { - ui.label(format!("Total User: {}", self.table_i().get_total_user())); - ui.separator(); - ui.label(format!("Total Message: {}", self.table_i().total_message)); - ui.separator(); - ui.label(format!( - "Whitelisted User: {}", - self.table_i().total_whitelisted_user - )); - ui.separator(); - ui.label(format!( - "Whitelisted Message: {}", - self.table_i().total_whitelisted_message - )); + for (label, hover, value) in stats { + ui.add(StatTile::new(label, value, tile_width).height(46.0)) + .on_hover_text(hover); + } }); - ui.separator(); + + ui.add_space(6.0); // Date section remains disabled while data processing is ongoing or the table is empty - ui.add_enabled_ui(date_enabled, |ui| { - ui.horizontal(|ui| { - let table = self.table(); - - ui.label("From:"); - ui.add( - DatePickerButton::new(table.date_nav.handler().from()).id_salt("1"), - ) - .on_hover_text("Show data only after this date, including the date itself"); - - ui.label("To:"); - ui.add(DatePickerButton::new(table.date_nav.handler().to()).id_salt("2")) - .on_hover_text("Show data only before this date, including the date itself"); - - let reset_button = ui.button("Reset Date Selection").on_hover_text("Reset selected date to the oldest and the newest date with at least 1 data point"); - if reset_button.clicked() { - table.date_nav.handler().reset_dates(); - table.create_rows(); - } + Card::new().show(ui, |ui| { + ui.add_enabled_ui(date_enabled, |ui| { + ui.horizontal(|ui| { + let table = self.table(); + + ui.label("From:"); + ui.add( + DatePickerButton::new(table.date_nav.handler().from()).id_salt("1"), + ) + .on_hover_text("Show data only after this date, including the date itself"); + + ui.label("To:"); + ui.add(DatePickerButton::new(table.date_nav.handler().to()).id_salt("2")) + .on_hover_text("Show data only before this date, including the date itself"); + + let reset_button = ui.button("Reset Date Selection").on_hover_text("Reset selected date to the oldest and the newest date with at least 1 data point"); + if reset_button.clicked() { + table.date_nav.handler().reset_dates(); + table.create_rows(); + } - ui.separator(); - - let hover_position = ui.make_persistent_id("nav_hovered_1"); - let selected_position = ui.make_persistent_id("nav_selected_1"); - for nav in NavigationType::iter() { - let selected = table.date_nav.nav_type_i() == nav; - let resp = ui.add(AnimatedLabel::new( - selected, - nav.to_string(), - selected_position, - hover_position, - 50.0, - 20.0, - None, - (false, false), - )); - - - if resp.clicked() { + if let Some(nav) = Tabs::new("nav_type_1", NavigationType::iter(), &table.date_nav.nav_type_i()) + .style(TabStyle::Segmented) + .min_item_width(50.0) + .equal_width(true) + .show(ui) + { *table.date_nav.nav_type() = nav; } - } - ui.separator(); + let previous_hover = format!("Go back by 1 {} from the current date. Shortcut key: CTRL + H", table.date_nav.nav_name()); + let next_hover = format!("Go next by 1 {} from the current date. Shortcut key: CTRL + L", table.date_nav.nav_name()); - let previous_hover = format!("Go back by 1 {} from the current date. Shortcut key: CTRL + H", table.date_nav.nav_name()); - let next_hover = format!("Go next by 1 {} from the current date. Shortcut key: CTRL + L", table.date_nav.nav_name()); - - if ui.button(format!("Previous {}", table.date_nav.nav_name())).on_hover_text(previous_hover).clicked() { - table.date_nav.go_previous(); - } + if ui.button(format!("Previous {}", table.date_nav.nav_name())).on_hover_text(previous_hover).clicked() { + table.date_nav.go_previous(); + } - if ui.button(format!("Next {}", table.date_nav.nav_name())).on_hover_text(next_hover).clicked() { - table.date_nav.go_next(); - } + if ui.button(format!("Next {}", table.date_nav.nav_name())).on_hover_text(next_hover).clicked() { + table.date_nav.go_next(); + } + }); }); }); - ui.separator(); + ui.add_space(6.0); ui.add_enabled_ui(date_enabled, |ui| { ui.horizontal(|ui| { let text_box = TextEdit::singleline(&mut self.table().search_query) + .desired_width(320.0) .hint_text("Search by name, username or user ID"); ui.add(text_box); @@ -657,6 +669,7 @@ impl MainWindow { .search_and_show(&column_list, &search_query, None, None); } } + if ui .button("Clear") .on_hover_text("Clear search result") @@ -668,18 +681,18 @@ impl MainWindow { }); }); - ui.separator(); + ui.add_space(6.0); // Monitor for H and L key presses if date_enabled { let is_ctrl_pressed = ui.ctx().input(|i| i.modifiers.ctrl); let key_h_pressed = ui.ctx().input(|i| i.key_pressed(Key::H)); + let key_l_pressed = ui.ctx().input(|i| i.key_pressed(Key::L)); - if key_h_pressed && is_ctrl_pressed { - self.table().date_nav.go_previous(); - } else { - let key_l_pressed = ui.ctx().input(|i| i.key_pressed(Key::L)); - if key_l_pressed && is_ctrl_pressed { + if is_ctrl_pressed { + if key_h_pressed { + self.table().date_nav.go_previous(); + } else if key_l_pressed { self.table().date_nav.go_next(); } } @@ -752,33 +765,30 @@ impl MainWindow { for selected in &table_selected_rows { let row_data = &selected.row_data; - if row_data.name != "Anonymous/Unknown" { + if row_data.name != "Anonymous/Unknown" && row_data.belongs_to.is_some() { selected_rows.push(row_data); } } let total_to_whitelist = selected_rows.len(); - let mut packed_chats = Vec::new(); - let mut all_ids = Vec::new(); + for row in selected_rows { - let cloned_row = row.clone(); all_ids.push(row.id); - self.whitelist.add_to_whitelist( + self.whitelist.add_user( row.name.clone(), row.username.clone(), row.id, - row.belongs_to.clone().unwrap(), + row.belongs_to.unwrap(), row.seen_by.clone(), ); - let hex_value = cloned_row.belongs_to.unwrap().pack().to_hex(); - packed_chats.push(PackedWhitelistedUser::new(hex_value, cloned_row.seen_by)); } + self.table().set_as_whitelisted(&all_ids); self.chart().reset_saved_bars(); - self.whitelist.save_whitelisted_users(false); - self.process_state = ProcessState::UsersWhitelisted(total_to_whitelist); + self.whitelist.save(false); + self.process_state = ProcessState::UsersListed(ListKind::Whitelist, total_to_whitelist); } /// Marks all the rows with at least 1 column selected as blacklisted @@ -788,32 +798,27 @@ impl MainWindow { for selected in &table_selected_rows { let row_data = &selected.row_data; - if row_data.name != "Anonymous/Unknown" { + if row_data.name != "Anonymous/Unknown" && row_data.belongs_to.is_some() { selected_rows.push(row_data); } } let total_to_blacklist = selected_rows.len(); - let mut packed_chats = Vec::new(); - let mut all_ids = Vec::new(); let mut names = Vec::new(); for row in selected_rows { let chart_name = to_chart_name(row.username.clone(), &row.name, row.id); names.push(chart_name); - let cloned_row = row.clone(); all_ids.push(row.id); - self.blacklist.add_to_blacklist( + self.blacklist.add_user( row.name.clone(), row.username.clone(), row.id, - row.belongs_to.clone().unwrap(), + row.belongs_to.unwrap(), row.seen_by.clone(), ); - let hex_value = cloned_row.belongs_to.unwrap().pack().to_hex(); - packed_chats.push(PackedBlacklistedUser::new(hex_value, cloned_row.seen_by)); } for chart in self.chart_all() { @@ -824,7 +829,7 @@ impl MainWindow { table.remove_blacklisted_rows(&all_ids); } - self.blacklist.save_blacklisted_users(false); - self.process_state = ProcessState::UsersBlacklisted(total_to_blacklist); + self.blacklist.save(false); + self.process_state = ProcessState::UsersListed(ListKind::Blacklist, total_to_blacklist); } } diff --git a/src/ui/widgets/card.rs b/src/ui/widgets/card.rs new file mode 100644 index 0000000..2bf5022 --- /dev/null +++ b/src/ui/widgets/card.rs @@ -0,0 +1,44 @@ +use eframe::egui::{CornerRadius, Frame, InnerResponse, Margin, RichText, Stroke, Ui}; + +pub struct Card { + title: Option, +} + +impl Card { + pub fn new() -> Self { + Self { title: None } + } + + pub fn title(mut self, title: impl Into) -> Self { + self.title = Some(title.into()); + self + } + + pub fn show(self, ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> InnerResponse { + let visuals = ui.visuals(); + let frame = Frame::new() + .fill(visuals.faint_bg_color) + .stroke(Stroke::new( + 1.0, + visuals.widgets.noninteractive.bg_stroke.color, + )) + .corner_radius(CornerRadius::same(8)) + .inner_margin(Margin::symmetric(12, 10)); + + frame.show(ui, |ui| { + // Frames only take the width they need, fill the whole row instead + ui.set_width(ui.available_width()); + + // Inputs sit on the card color instead of the panel color and lose their + // contrast, so give idle widgets a visible outline + let outline = ui.visuals().widgets.noninteractive.bg_stroke.color; + ui.visuals_mut().widgets.inactive.bg_stroke = Stroke::new(1.0, outline); + + if let Some(title) = self.title { + ui.label(RichText::new(title).size(13.0).strong()); + ui.add_space(6.0); + } + add_contents(ui) + }) + } +} diff --git a/src/ui/widgets/mod.rs b/src/ui/widgets/mod.rs new file mode 100644 index 0000000..bdecc25 --- /dev/null +++ b/src/ui/widgets/mod.rs @@ -0,0 +1,13 @@ +mod card; +mod primary_button; +mod row_label; +mod stat_tile; +mod status_line; +mod tabs; + +pub use card::*; +pub use primary_button::*; +pub use row_label::*; +pub use stat_tile::*; +pub use status_line::*; +pub use tabs::*; diff --git a/src/ui/widgets/primary_button.rs b/src/ui/widgets/primary_button.rs new file mode 100644 index 0000000..cabba95 --- /dev/null +++ b/src/ui/widgets/primary_button.rs @@ -0,0 +1,93 @@ +use eframe::egui::{ + Align2, Color32, CornerRadius, CursorIcon, Response, Role, Sense, TextStyle, Ui, Vec2, Widget, + WidgetInfo, +}; + +pub struct PrimaryButton { + text: String, + size: Vec2, + danger: bool, +} + +impl PrimaryButton { + pub fn new(text: impl Into) -> Self { + Self { + text: text.into(), + size: Vec2::new(100.0, 36.0), + danger: false, + } + } + + pub fn size(mut self, size: Vec2) -> Self { + self.size = size; + self + } + + pub fn danger(mut self, danger: bool) -> Self { + self.danger = danger; + self + } +} + +impl Widget for PrimaryButton { + fn ui(self, ui: &mut Ui) -> Response { + let Self { text, size, danger } = self; + + let enabled = ui.is_enabled(); + let sense = if enabled { + Sense::click() + } else { + Sense::hover() + }; + + let (rect, response) = ui.allocate_exact_size(size, sense); + response.widget_info(|| WidgetInfo::labeled(Role::Button, enabled, &text)); + + if ui.is_rect_visible(rect) { + let visuals = ui.visuals(); + + let base = if danger { + Color32::from_rgb(190, 70, 70) + } else { + visuals.selection.bg_fill + }; + let hover = base.lerp_to_gamma(Color32::WHITE, 0.18); + let pressed = base.lerp_to_gamma(Color32::BLACK, 0.15); + + let hover_t = ui.ctx().animate_bool_with_time( + response.id.with("hover"), + response.hovered() && enabled, + 0.12, + ); + + let mut fill = base.lerp_to_gamma(hover, hover_t); + if response.is_pointer_button_down_on() { + fill = pressed; + } + + let mut text_color = visuals.selection.stroke.color; + if danger { + text_color = Color32::WHITE; + } + if !enabled { + fill = visuals.widgets.noninteractive.weak_bg_fill; + text_color = visuals.widgets.noninteractive.fg_stroke.color; + } + + ui.painter().rect_filled(rect, CornerRadius::same(8), fill); + ui.painter().text( + rect.center(), + Align2::CENTER_CENTER, + &text, + TextStyle::Button.resolve(ui.style()), + text_color, + ); + } + + if enabled { + response.on_hover_cursor(CursorIcon::PointingHand) + } else { + response + } + } +} diff --git a/src/ui/widgets/row_label.rs b/src/ui/widgets/row_label.rs new file mode 100644 index 0000000..ce3c5f5 --- /dev/null +++ b/src/ui/widgets/row_label.rs @@ -0,0 +1,106 @@ +use eframe::egui::{ + Color32, CornerRadius, Response, Role, Sense, StrokeKind, TextStyle, Ui, Widget, WidgetInfo, + WidgetText, +}; +use eframe::emath::NumExt; + +const FADE_TIME: f32 = 0.12; + +pub struct RowLabel { + text: WidgetText, + selected: bool, + whitelisted: bool, +} + +impl RowLabel { + pub fn new(selected: bool, whitelisted: bool, text: impl Into) -> Self { + Self { + selected, + text: text.into(), + whitelisted, + } + } +} + +impl Widget for RowLabel { + fn ui(self, ui: &mut Ui) -> Response { + let Self { + selected, + text, + whitelisted, + } = self; + let button_padding = ui.spacing().button_padding; + let total_extra = button_padding + button_padding; + + let wrap_width = ui.available_width() - total_extra.x; + let text = text.into_galley(ui, None, wrap_width, TextStyle::Button); + + let mut desired_size = total_extra + text.size(); + desired_size.y = desired_size.y.at_least(ui.spacing().interact_size.y); + let (rect, response) = ui.allocate_at_least(desired_size, Sense::click()); + response.widget_info(|| { + WidgetInfo::selected(Role::Button, ui.is_enabled(), selected, text.text()) + }); + + if ui.is_rect_visible(response.rect) { + let text_pos = ui + .layout() + .align_size_within_rect(text.size(), rect.shrink2(button_padding)) + .min; + + let visuals = ui.visuals(); + let dark = visuals.dark_mode; + let accent = if dark { + Color32::from_rgb(232, 140, 90) + } else { + Color32::from_rgb(214, 106, 52) + }; + + let hover_t = ui.ctx().animate_bool_with_time( + response.id.with("hover"), + response.hovered() || response.highlighted() || response.has_focus(), + FADE_TIME, + ); + + let band = rect; + let radius = CornerRadius::same(4); + let hover_fill = visuals.widgets.hovered.weak_bg_fill; + + if whitelisted { + let tint = if dark { 0.20 } else { 0.18 }; + ui.painter() + .rect_filled(band, radius, accent.gamma_multiply(tint)); + } + + if hover_t > 0.0 && !selected { + let fill = if whitelisted { + accent.gamma_multiply(0.18 * hover_t) + } else { + hover_fill.gamma_multiply(hover_t) + }; + ui.painter().rect_filled(band, radius, fill); + } + + if selected { + let selection = visuals.selection; + ui.painter() + .rect_filled(band, radius, selection.bg_fill.gamma_multiply(0.85)); + ui.painter().rect_stroke( + band, + radius, + eframe::egui::Stroke::new(1.0, selection.stroke.color.gamma_multiply(0.6)), + StrokeKind::Inside, + ); + } + + let text_color = if selected { + visuals.selection.stroke.color + } else { + visuals.widgets.inactive.text_color() + }; + ui.painter().galley(text_pos, text, text_color); + } + + response + } +} diff --git a/src/ui/widgets/stat_tile.rs b/src/ui/widgets/stat_tile.rs new file mode 100644 index 0000000..6c663ec --- /dev/null +++ b/src/ui/widgets/stat_tile.rs @@ -0,0 +1,76 @@ +use eframe::egui::{ + Align2, CornerRadius, Response, Sense, StrokeKind, TextStyle, Ui, Widget, vec2, +}; + +pub struct StatTile { + label: String, + value: String, + width: f32, + height: f32, +} + +impl StatTile { + pub fn new(label: impl Into, value: impl ToString, width: f32) -> Self { + Self { + label: label.into(), + value: value.to_string(), + width, + height: 54.0, + } + } + + pub fn height(mut self, height: f32) -> Self { + self.height = height; + self + } +} + +impl Widget for StatTile { + fn ui(self, ui: &mut Ui) -> Response { + let Self { + label, + value, + width, + height, + } = self; + + let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::hover()); + + if ui.is_rect_visible(rect) { + let visuals = ui.visuals(); + let radius = CornerRadius::same(8); + + ui.painter() + .rect_filled(rect, radius, visuals.faint_bg_color); + ui.painter().rect_stroke( + rect, + radius, + visuals.widgets.noninteractive.bg_stroke, + StrokeKind::Inside, + ); + + let mut caption = TextStyle::Body.resolve(ui.style()); + caption.size = 13.0; + let number = TextStyle::Heading.resolve(ui.style()); + let weak = visuals.text_color(); + let strong = visuals.strong_text_color(); + + ui.painter().text( + rect.center_top() + vec2(0.0, 7.0), + Align2::CENTER_TOP, + label, + caption, + weak, + ); + ui.painter().text( + rect.center_bottom() - vec2(0.0, 7.0), + Align2::CENTER_BOTTOM, + value, + number, + strong, + ); + } + + response + } +} diff --git a/src/ui/widgets/status_line.rs b/src/ui/widgets/status_line.rs new file mode 100644 index 0000000..280d429 --- /dev/null +++ b/src/ui/widgets/status_line.rs @@ -0,0 +1,44 @@ +use eframe::egui::{Align, Color32, Label, Layout, Response, Sense, Ui, UiBuilder, Widget, vec2}; + +/// Single line status text with a colored dot in front. Long text is cut off and the +/// full text is shown on hover +pub struct StatusLine { + text: String, + dot: Color32, + width: f32, +} + +impl StatusLine { + pub fn new(text: impl Into, dot: Color32, width: f32) -> Self { + Self { + text: text.into(), + dot, + width, + } + } +} + +impl Widget for StatusLine { + fn ui(self, ui: &mut Ui) -> Response { + let Self { text, dot, width } = self; + let size = vec2(width.max(0.0), ui.spacing().interact_size.y); + + // The full width is reserved up front. Sizing it by its content would make whatever + // comes next move around every time the text changes + let (rect, response) = ui.allocate_exact_size(size, Sense::hover()); + + ui.scope_builder( + UiBuilder::new() + .max_rect(rect) + .layout(Layout::left_to_right(Align::Center)), + |ui| { + let (dot_rect, _) = ui.allocate_exact_size(vec2(10.0, 10.0), Sense::hover()); + ui.painter().circle_filled(dot_rect.center(), 4.0, dot); + + ui.add(Label::new(text).truncate()); + }, + ); + + response + } +} diff --git a/src/ui/widgets/tabs.rs b/src/ui/widgets/tabs.rs new file mode 100644 index 0000000..33cfc61 --- /dev/null +++ b/src/ui/widgets/tabs.rs @@ -0,0 +1,300 @@ +use eframe::egui::{ + Color32, CornerRadius, CursorIcon, Rect, Response, Role, Sense, StrokeKind, TextStyle, Ui, + Vec2, WidgetInfo, pos2, vec2, +}; +use std::fmt::Display; + +/// Seconds the selection indicator takes to slide to a new tab +const SLIDE_TIME: f64 = 0.22; +/// Seconds for the hover highlight and the text color to fade +const FADE_TIME: f32 = 0.15; + +#[derive(Clone, Copy, Default, PartialEq, Eq)] +pub enum TabStyle { + /// Plain text with a sliding accent pill behind the selected tab + #[default] + Pill, + /// Items inside a rounded track with a sliding pill behind the selected one + Segmented, +} + +/// Animated row of mutually exclusive tabs. +pub struct Tabs { + id_salt: &'static str, + items: Vec, + selected: usize, + style: TabStyle, + min_item_width: f32, + equal_width: bool, + centered: bool, + hover_text: Option>, +} + +type HoverText = Box String>; + +/// Where the indicator was drawn last frame and where it is coming from +#[derive(Clone, Copy)] +struct SlideState { + target: usize, + from: (f32, f32), + last: (f32, f32), + started_at: f64, +} + +impl Tabs { + pub fn new(id_salt: &'static str, items: impl IntoIterator, selected: &T) -> Self { + let items: Vec = items.into_iter().collect(); + let selected = items.iter().position(|item| item == selected).unwrap_or(0); + + Self { + id_salt, + items, + selected, + style: TabStyle::default(), + min_item_width: 0.0, + equal_width: false, + centered: false, + hover_text: None, + } + } + + pub fn style(mut self, style: TabStyle) -> Self { + self.style = style; + self + } + + pub fn min_item_width(mut self, width: f32) -> Self { + self.min_item_width = width; + self + } + + /// Give every item the width of the widest one + pub fn equal_width(mut self, equal: bool) -> Self { + self.equal_width = equal; + self + } + + /// Center the strip in the row it is placed in. It never moves left of where it + /// would start otherwise, so widgets placed before it are not overlapped + pub fn centered(mut self, centered: bool) -> Self { + self.centered = centered; + self + } + + /// Tooltip shown when hovering an item + pub fn hover_text(mut self, hover_text: impl Fn(&T) -> String + 'static) -> Self { + self.hover_text = Some(Box::new(hover_text)); + self + } + + /// Draws the tabs and returns the item that was clicked this frame + pub fn show(self, ui: &mut Ui) -> Option { + let Self { + id_salt, + mut items, + selected, + style, + min_item_width, + equal_width, + centered, + hover_text, + } = self; + + if items.is_empty() { + return None; + } + + let id = ui.make_persistent_id(id_salt); + let pad_x = match style { + TabStyle::Pill => 14.0, + TabStyle::Segmented => 10.0, + }; + let height = ui.spacing().interact_size.y + 4.0; + let font = TextStyle::Button.resolve(ui.style()); + + // Text color is overridden at paint time so it can fade between states + let galleys: Vec<_> = items + .iter() + .map(|item| { + ui.painter() + .layout_no_wrap(item.to_string(), font.clone(), Color32::PLACEHOLDER) + }) + .collect(); + + let widest = galleys + .iter() + .map(|galley| galley.size().x) + .fold(0.0, f32::max); + + let widths: Vec = galleys + .iter() + .map(|galley| { + let text_width = if equal_width { widest } else { galley.size().x }; + (text_width + pad_x * 2.0).max(min_item_width) + }) + .collect(); + + // The segmented track has a small inset so the pill does not touch the border + let (inset_x, inset_y) = match style { + TabStyle::Segmented => (3.0, 3.0), + TabStyle::Pill => (0.0, 2.0), + }; + let total_width = widths.iter().sum::() + inset_x * 2.0; + + let (mut strip, _) = ui.allocate_exact_size(vec2(total_width, height), Sense::hover()); + + if centered { + let row = ui.max_rect(); + let target_left = row.center().x - total_width / 2.0; + let max_shift = (row.right() - strip.right()).max(0.0); + let shift = (target_left - strip.left()).clamp(0.0, max_shift); + strip = strip.translate(vec2(shift, 0.0)); + } + + let mut x = strip.left() + inset_x; + let rects: Vec = widths + .iter() + .map(|width| { + let rect = Rect::from_min_size( + pos2(x, strip.top() + inset_y), + Vec2::new(*width, height - inset_y * 2.0), + ); + x += width; + rect + }) + .collect(); + + // Interaction first, painting afterwards, since the indicator is drawn under the text + let mut clicked = None; + let mut responses: Vec = Vec::with_capacity(items.len()); + for (i, rect) in rects.iter().enumerate() { + let response = ui + .interact(*rect, id.with(("item", i)), Sense::click()) + .on_hover_cursor(CursorIcon::PointingHand); + + let response = match &hover_text { + Some(hover_text) => response.on_hover_text(hover_text(&items[i])), + None => response, + }; + + let label = items[i].to_string(); + response.widget_info(|| { + WidgetInfo::selected(Role::Tab, ui.is_enabled(), i == selected, &label) + }); + + if response.clicked() { + clicked = Some(i); + } + responses.push(response); + } + + if !ui.is_rect_visible(strip) { + return clicked.map(|i| items.swap_remove(i)); + } + + let visuals = ui.visuals().clone(); + let accent = visuals.selection.bg_fill; + let ctx = ui.ctx().clone(); + + let (track_radius, pill_radius) = (CornerRadius::same(7), CornerRadius::same(5)); + + match style { + // No track or lines, the panel around the tabs already has its own border + TabStyle::Pill => {} + TabStyle::Segmented => { + ui.painter() + .rect_filled(strip, track_radius, visuals.extreme_bg_color); + ui.painter().rect_stroke( + strip, + track_radius, + visuals.widgets.noninteractive.bg_stroke, + StrokeKind::Inside, + ); + } + } + + // Hover highlight fades in and out on each item independently + for (i, response) in responses.iter().enumerate() { + let hover_t = ctx.animate_bool_with_time( + id.with(("hover", i)), + response.hovered() && i != selected, + FADE_TIME, + ); + if hover_t > 0.0 { + let color = visuals.widgets.hovered.weak_bg_fill.gamma_multiply(hover_t); + ui.painter().rect_filled(rects[i], pill_radius, color); + } + } + + // Slide the indicator from where it was last drawn to the selected item + let now = ctx.input(|i| i.time); + let target = rects[selected]; + // Relative to the strip so the indicator does not slide when the strip itself moves, + // for example when the window is resized by switching tabs + let origin = strip.left(); + let target_x = (target.left() - origin, target.right() - origin); + + let mut state = ctx + .data_mut(|d| d.get_temp::(id)) + .unwrap_or(SlideState { + target: selected, + from: target_x, + last: target_x, + started_at: now - SLIDE_TIME, + }); + + if state.target != selected { + state.from = state.last; + state.target = selected; + state.started_at = now; + } + + let progress = (((now - state.started_at) / SLIDE_TIME) as f32).clamp(0.0, 1.0); + let eased = ease_out_cubic(progress); + let left = lerp(state.from.0, target_x.0, eased); + let right = lerp(state.from.1, target_x.1, eased); + state.last = (left, right); + let (left, right) = (left + origin, right + origin); + + if progress < 1.0 { + ctx.request_repaint(); + } + ctx.data_mut(|d| d.insert_temp(id, state)); + + let pill = Rect::from_min_max(pos2(left, target.top()), pos2(right, target.bottom())); + ui.painter().rect_filled(pill, pill_radius, accent); + + // Text fades between its idle, hovered and selected colors + let idle = visuals.widgets.inactive.fg_stroke.color; + let hovered = visuals.widgets.hovered.fg_stroke.color; + let selected_color = visuals.selection.stroke.color; + + for (i, (galley, rect)) in galleys.into_iter().zip(&rects).enumerate() { + let select_t = + ctx.animate_bool_with_time(id.with(("select", i)), i == selected, FADE_TIME); + let hover_t = ctx.animate_bool_with_time( + id.with(("text_hover", i)), + responses[i].hovered(), + FADE_TIME, + ); + + let color = idle + .lerp_to_gamma(hovered, hover_t) + .lerp_to_gamma(selected_color, select_t); + + let text_pos = rect.center() - galley.size() / 2.0; + ui.painter() + .galley_with_override_text_color(text_pos, galley, color); + } + + clicked.map(|i| items.swap_remove(i)) + } +} + +fn lerp(from: f32, to: f32, t: f32) -> f32 { + from + (to - from) * t +} + +fn ease_out_cubic(t: f32) -> f32 { + 1.0 - (1.0 - t).powi(3) +} diff --git a/src/ui_components/keys_ui.rs b/src/ui_components/keys_ui.rs deleted file mode 100644 index 1caea96..0000000 --- a/src/ui_components/keys_ui.rs +++ /dev/null @@ -1,75 +0,0 @@ -use eframe::egui::{Align, Button, CentralPanel, Grid, Label, Layout, TextEdit, Ui, vec2}; -use serde::{Deserialize, Serialize}; - -use crate::ui_components::MainWindow; -use crate::ui_components::processor::AppState; -use crate::utils::save_api_keys; - -#[derive(Deserialize, Serialize, Default)] -pub struct TGKeys { - pub api_id: String, - pub api_hash: String, -} - -impl MainWindow { - pub fn show_tg_keys_ui(&mut self, ui: &mut Ui) { - CentralPanel::default().show(ui, |ui| { - let tg_link = "https://my.telegram.org/"; - ui.label("A valid Telegram API key pair is necessary for the app to work properly. \ - The key will be saved locally and will never be shared. \ - To get your API key, visit the link below ➡ API development tools ➡ Create a new application"); - - ui.add_space(20.0); - Grid::new("Keys Grid") - .num_columns(2) - .spacing([5.0, 10.0]) - .show(ui, |ui| { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("API Link:")); - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - if ui.link(tg_link).clicked() { - open::that(tg_link).unwrap(); - } - }); - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("API ID:")); - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - ui.add( - TextEdit::singleline(&mut self.tg_keys.api_id) - .hint_text("12345678") - .min_size(ui.available_size()), - ); - }); - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("API Hash:")); - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - ui.add( - TextEdit::singleline(&mut self.tg_keys.api_hash) - .hint_text("12345abcdef") - .min_size(ui.available_size()), - ); - }); - ui.end_row(); - }); - ui.add_space(20.0); - ui.vertical_centered(|ui| { - if ui - .add_sized(vec2(80.0, 40.0), Button::new("Save Keys")) - .clicked() - && !self.tg_keys.api_hash.is_empty() - && !self.tg_keys.api_id.is_empty() - { - save_api_keys(&self.tg_keys); - self.app_state = AppState::InitializedUI; - } - }); - }); - } -} diff --git a/src/ui_components/mod.rs b/src/ui_components/mod.rs deleted file mode 100644 index 12df202..0000000 --- a/src/ui_components/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -mod initializer; -mod keys_ui; -pub mod processor; -pub mod tab_ui; -mod widgets; - -pub use initializer::*; -pub use keys_ui::*; diff --git a/src/ui_components/processor/font_dl.rs b/src/ui_components/processor/font_dl.rs deleted file mode 100644 index cbd9643..0000000 --- a/src/ui_components/processor/font_dl.rs +++ /dev/null @@ -1,83 +0,0 @@ -use eframe::egui::{Context, FontData, FontDefinitions}; -use eframe::epaint::FontFamily; -use log::{error, info}; -use std::fs::File; -use std::io::Write; -use std::path::PathBuf; -use std::sync::Arc; - -/// Downloads the app font data from github, saves them locally and loads them -pub async fn download_font(ctx: Context) { - let cjk_font_url = - "https://github.com/TheRustyPickle/Talon/raw/main/fonts/NotoSansCJK-Regular.ttc"; - let gentium_font_url = - "https://github.com/TheRustyPickle/Talon/raw/main/fonts/GentiumBookPlus-Regular.ttf"; - - let mut gentium_font = PathBuf::from("."); - let mut cjk_font = PathBuf::from("."); - - gentium_font.push("fonts"); - cjk_font.push("fonts"); - - gentium_font.push("GentiumBookPlus-Regular.ttf"); - cjk_font.push("NotoSansCJK-Regular.ttc"); - - let client = reqwest::Client::new(); - - let Ok(response) = client.get(cjk_font_url).send().await else { - error!("Failed to get a response for CJK font"); - return; - }; - - let cjk_data = if response.status().is_success() { - let mut file = File::create(cjk_font).unwrap(); - let response_data = response - .bytes() - .await - .expect("Could not convert CJK response into bytes"); - file.write_all(&response_data).unwrap(); - info!("Saved CJK font data successfully"); - response_data - } else { - error!("CJK response was not a success"); - return; - }; - - let Ok(response) = client.get(gentium_font_url).send().await else { - error!("Failed to get a response for Gentium font"); - return; - }; - - let gentium_data = if response.status().is_success() { - let mut file = File::create(gentium_font).unwrap(); - let response_data = response - .bytes() - .await - .expect("Could not convert gentium response into bytes"); - file.write_all(&response_data).unwrap(); - info!("Saved Gentium font data successfully"); - response_data - } else { - error!("Gentium response was not a success"); - return; - }; - - let font_cjk = Arc::new(FontData::from_owned(cjk_data.to_vec())); - let font_gentium = Arc::new(FontData::from_owned(gentium_data.to_vec())); - let mut font_definitions = FontDefinitions::default(); - - font_definitions - .font_data - .insert("NotoSansCJK".to_owned(), font_cjk); - font_definitions - .font_data - .insert("GentiumBookPlus".to_owned(), font_gentium); - - font_definitions - .families - .get_mut(&FontFamily::Proportional) - .unwrap() - .extend(["NotoSansCJK".to_owned(), "GentiumBookPlus".to_owned()]); - - ctx.set_fonts(font_definitions); -} diff --git a/src/ui_components/processor/mod.rs b/src/ui_components/processor/mod.rs deleted file mode 100644 index 64b0721..0000000 --- a/src/ui_components/processor/mod.rs +++ /dev/null @@ -1,16 +0,0 @@ -mod counter_counts; -mod date_handler; -mod date_navigator; -mod font_dl; -mod parsed_chat; -mod states; -mod tg_comms; -mod version_checker; - -pub use counter_counts::*; -pub use date_handler::*; -pub use date_navigator::*; -pub use font_dl::*; -pub use parsed_chat::*; -pub use states::*; -pub use version_checker::*; diff --git a/src/ui_components/processor/states.rs b/src/ui_components/processor/states.rs deleted file mode 100644 index 1526564..0000000 --- a/src/ui_components/processor/states.rs +++ /dev/null @@ -1,337 +0,0 @@ -use eframe::egui::{Vec2, vec2}; -use grammers_client::types::Chat; -use serde::{Deserialize, Serialize}; -use std::fmt::{self, Display}; -use strum_macros::{Display as sDisplay, EnumIter}; - -#[derive(Default)] -pub enum AppState { - #[default] - LoadingFontsAPI, - InputAPIKeys, - InitializedUI, -} - -#[derive(PartialEq, EnumIter, sDisplay)] -pub enum TabState { - Counter, - #[strum(to_string = "User Table")] - UserTable, - Charts, - Whitelist, - Blacklist, - Session, -} - -impl TabState { - pub fn first_value() -> Self { - TabState::Counter - } - - pub fn window_size(&self) -> Vec2 { - match self { - TabState::Counter => vec2(550.0, 400.0), - TabState::UserTable => vec2(1250.0, 700.0), - TabState::Charts => vec2(1000.0, 700.0), - TabState::Whitelist | TabState::Blacklist => vec2(550.0, 600.0), - TabState::Session => vec2(550.0, 320.0), - } - } -} - -pub enum ProcessState { - Idle, - InitialClientConnectionSuccessful(String), - Counting(u8), - InvalidStartChat, - DataCopied, - AuthorizationError, - FileCreationFailed, - UnauthorizedClient(String), - NonExistingChat(String), - SendingTGCode, - TGCodeSent, - LogInWithCode, - LogInWithPassword, - InvalidTGCode, - InvalidPassword, - NotSignedUp, - UnknownError, - LoggedIn(String), - EmptySelectedSession, - InvalidPhoneOrAPI, - InvalidAPIKeys, - PasswordRequired, - FloodWait, - UsersWhitelisted(usize), - UsersBlacklisted(usize), - LoadedWhitelistedUsers(usize, i32), - LoadedBlacklistedUsers(usize, i32), - FailedLoadWhitelistedUsers, - FailedLoadBlacklistedUsers, - WhitelistedUserRemoved(usize), - BlacklistedUserRemoved(usize), - AllWhitelistRemoved, - AllBlacklistRemoved, - AddedToWhitelist, - AddedToBlacklist, - LatestMessageLoadingFailed, - DataExported(String), -} - -impl ProcessState { - pub fn next_dot(&self) -> Self { - match self { - ProcessState::Counting(num) => { - let new_num = if num == &3 { 0 } else { num + 1 }; - ProcessState::Counting(new_num) - } - _ => ProcessState::Counting(0), - } - } -} - -impl Display for ProcessState { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ProcessState::Idle => write!(f, "Status: Idle"), - ProcessState::InitialClientConnectionSuccessful(text) => { - write!(f, "Status: {text}",) - } - ProcessState::Counting(count) => { - write!(f, "Status: Checking messages")?; - for _ in 0..*count { - write!(f, ".")?; - } - Ok(()) - } - ProcessState::InvalidStartChat => { - write!(f, "Status: Could not detect any valid chat details") - } - ProcessState::DataCopied => { - write!(f, "Status: Selected table data copied.") - } - ProcessState::AuthorizationError => write!( - f, - "Status: Could not connect to the session. Are your API keys valid?" - ), - ProcessState::FileCreationFailed => { - write!(f, "Status: Could not create the session file. Try again") - } - ProcessState::UnauthorizedClient(name) => write!( - f, - "Status: The session {name} is not authorized. Delete the session and create a new one" - ), - ProcessState::NonExistingChat(name) => { - write!(f, "Status: The target chat {name} does not exist") - } - ProcessState::SendingTGCode => write!(f, "Status: Trying to send Telegram login code"), - ProcessState::TGCodeSent => write!(f, "Status: Telegram code was sent"), - ProcessState::LogInWithCode => { - write!(f, "Status: Trying to login to the session with the code") - } - ProcessState::LogInWithPassword => { - write!(f, "Trying to login to the session with the password") - } - ProcessState::LoggedIn(name) => write!(f, "Status: Logged in session {name}"), - ProcessState::InvalidTGCode => write!(f, "Status: Invalid TG Code given"), - ProcessState::InvalidPassword => write!(f, "Status: Invalid password given"), - ProcessState::NotSignedUp => { - write!(f, "Status: Account not signed up with this phone number") - } - ProcessState::UnknownError => write!(f, "Status: Unknown error acquired"), - ProcessState::EmptySelectedSession => write!( - f, - "Status: No session is selected. Create a new session from the Session tab" - ), - ProcessState::InvalidPhoneOrAPI => write!( - f, - "Status: Unknown error acquired. Possibly invalid phone number given or API keys are invalid" - ), - ProcessState::InvalidAPIKeys => write!( - f, - "Status: Failed to parse saved API keys. Are the API keys valid?" - ), - ProcessState::PasswordRequired => { - write!(f, "Status: Account requires a password authentication") - } - ProcessState::FloodWait => { - write!(f, "Status: Flood wait triggered. Will resume again soon") - } - ProcessState::UsersWhitelisted(num) => write!(f, "Status: Whitelisted {num} users"), - ProcessState::UsersBlacklisted(num) => write!(f, "Status: Blacklisted {num} users"), - ProcessState::LoadedWhitelistedUsers(success, failed) => write!( - f, - "Status: Loaded {success} whitelisted users. Failed to load {failed} users" - ), - ProcessState::LoadedBlacklistedUsers(success, failed) => write!( - f, - "Status: Loaded {success} blacklisted users. Failed to load {failed} users" - ), - ProcessState::FailedLoadWhitelistedUsers => write!( - f, - "Status: Failed to load whitelisted users due to invalid saved data. Old data has been removed" - ), - ProcessState::FailedLoadBlacklistedUsers => write!( - f, - "Status: Failed to load blacklisted users due to invalid saved data. Old data has been removed" - ), - ProcessState::WhitelistedUserRemoved(num) => { - write!(f, "Status: {num} whitelisted users removed") - } - ProcessState::BlacklistedUserRemoved(num) => { - write!(f, "Status: {num} blacklisted users removed") - } - ProcessState::AllWhitelistRemoved => write!(f, "Status: All whitelisted users removed"), - ProcessState::AllBlacklistRemoved => write!(f, "Status: All blacklisted users removed"), - ProcessState::AddedToWhitelist => write!(f, "Status: User added to whitelist"), - ProcessState::AddedToBlacklist => write!(f, "Status: User added to blacklist"), - ProcessState::LatestMessageLoadingFailed => { - write!(f, "Status: Failed to get the latest message") - } - ProcessState::DataExported(location) => { - write!(f, "Status: Data exported to {location}") - } - } - } -} - -#[derive(EnumIter, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Copy)] -pub enum ColumnName { - #[default] - Name, - Username, - UserID, - TotalMessage, - TotalWord, - TotalChar, - AverageWord, - AverageChar, - FirstMessageSeen, - LastMessageSeen, - Whitelisted, -} - -impl fmt::Display for ColumnName { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let name = match self { - ColumnName::Name => "Name", - ColumnName::Username => "Username", - ColumnName::UserID => "User ID", - ColumnName::TotalMessage => "Total Message", - ColumnName::TotalWord => "Total Word", - ColumnName::TotalChar => "Total Char", - ColumnName::AverageWord => "Average Word", - ColumnName::AverageChar => "Average Char", - ColumnName::FirstMessageSeen => "First Message Seen", - ColumnName::LastMessageSeen => "Last Message Seen", - ColumnName::Whitelisted => "Whitelisted", - }; - write!(f, "{name}") - } -} - -#[derive(Default, PartialEq, Clone, Copy)] -pub enum ChartType { - #[default] - Message, - ActiveUser, - MessageWeekDay, - ActiveUserWeekDay, -} - -impl Display for ChartType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ChartType::Message => write!(f, "Message"), - ChartType::ActiveUser => write!(f, "Active User"), - ChartType::MessageWeekDay => write!(f, "Message Weekday"), - ChartType::ActiveUserWeekDay => write!(f, "Active User Weekday"), - } - } -} - -#[derive(Default, PartialEq, Copy, Clone)] -pub enum ChartTiming { - #[default] - Hourly, - Daily, - Weekly, - Monthly, -} - -impl Display for ChartTiming { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - ChartTiming::Daily => write!(f, "Daily"), - ChartTiming::Hourly => write!(f, "Hourly"), - ChartTiming::Weekly => write!(f, "Weekly"), - ChartTiming::Monthly => write!(f, "Monthly"), - } - } -} - -#[derive(Deserialize, Serialize, PartialEq, Eq, Hash)] -pub struct PackedWhitelistedUser { - pub hex_value: String, - pub seen_by: String, -} - -impl PackedWhitelistedUser { - pub fn new(hex_value: String, seen_by: String) -> Self { - Self { hex_value, seen_by } - } -} - -pub struct UnpackedWhitelistedUser { - pub user_chat: Chat, - pub seen_by: String, -} - -impl UnpackedWhitelistedUser { - pub fn new(user_chat: Chat, seen_by: String) -> Self { - Self { user_chat, seen_by } - } -} - -#[derive(Deserialize, Serialize, PartialEq, Eq, Hash)] -pub struct PackedBlacklistedUser { - pub hex_value: String, - pub seen_by: String, -} - -impl PackedBlacklistedUser { - pub fn new(hex_value: String, seen_by: String) -> Self { - Self { hex_value, seen_by } - } -} - -pub struct UnpackedBlacklistedUser { - pub user_chat: Chat, - pub seen_by: String, -} - -impl UnpackedBlacklistedUser { - pub fn new(user_chat: Chat, seen_by: String) -> Self { - Self { user_chat, seen_by } - } -} -#[derive(EnumIter, Default, PartialEq, Copy, Clone)] -pub enum NavigationType { - #[default] - Day, - Week, - Month, - Year, -} - -impl Display for NavigationType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - NavigationType::Day => write!(f, "Day"), - NavigationType::Week => write!(f, "Week"), - NavigationType::Month => write!(f, "Month"), - NavigationType::Year => write!(f, "Year"), - } - } -} diff --git a/src/ui_components/processor/tg_comms.rs b/src/ui_components/processor/tg_comms.rs deleted file mode 100644 index c5a93a4..0000000 --- a/src/ui_components/processor/tg_comms.rs +++ /dev/null @@ -1,443 +0,0 @@ -use chrono::{Local, TimeZone}; -use log::{error, info}; -use std::fmt::Write as _; -use std::sync::atomic::Ordering; - -use crate::tg_handler::{ProcessError, ProcessResult, ProcessStart}; -use crate::ui_components::MainWindow; -use crate::ui_components::processor::ProcessState; -use crate::utils::to_chart_name; - -impl MainWindow { - /// Checks if there are any new message from the async side - pub fn check_receiver(&mut self) -> bool { - if let Ok(data) = self.tg_receiver.try_recv() { - match data { - ProcessResult::InitialSessionSuccess((clients, success, failed)) => { - let mut status_text = if success.is_empty() { - String::new() - } else { - format!("Successfully connected to: {}.", success.join(", ")) - }; - - if !failed.is_empty() { - let _ = write!(status_text, " Failed connection to: {}", failed.join(", ")); - } - - for client in clients { - self.tg_clients.insert(client.name(), client); - } - - self.process_state = - ProcessState::InitialClientConnectionSuccessful(status_text); - self.load_whitelisted_users(); - self.load_blacklisted_users(); - } - ProcessResult::InvalidChat(chat_name) => { - info!("Invalid chat name found: {chat_name}"); - self.process_state = ProcessState::NonExistingChat(chat_name); - self.go_next_or_stop(); - } - ProcessResult::UnauthorizedClient(client_name) => { - info!("{client_name} is not authorized."); - self.process_state = ProcessState::UnauthorizedClient(client_name); - self.stop_process(); - } - ProcessResult::CountingEnd((end_at, last_number)) => { - // Example case end point 100, last processed 102 - // Current num 99 so end point reached - // 101 and 100 is missing so count them as deleted - if last_number != end_at { - let total_deleted = last_number - end_at; - self.t_count().add_deleted_message(total_deleted); - } - - info!("Counting ended for a session"); - - // Stop process sets the progress bar to 100 - // Progress only if 1 session is remaining to be completed or it was 0 (0 in normal counting) - // Also recreate table data after counting session ends for a chat - if self.counter.session_remaining() <= 1 { - self.t_table().create_rows(); - let total_user = self.t_table().get_total_users_full(); - self.t_count().set_total_user(total_user as i32); - self.go_next_or_stop(); - } else { - self.counter.reduce_session(); - } - } - ProcessResult::CountingMessage(count_data) => { - self.process_state = self.process_state.next_dot(); - - let message = count_data.message(); - let start_from = count_data.start_at(); - let end_at = count_data.end_at(); - let last_number = count_data.last_number(); - let multi_session = count_data.multi_session(); - - let message_sent_at = message.date().naive_utc(); - let local_time_date = Local.from_utc_datetime(&message_sent_at).date_naive(); - let local_time_datetime = - Local.from_utc_datetime(&message_sent_at).naive_local(); - - let sender = message.sender(); - - let user_id = if let Some(c) = &sender { c.id() } else { 0 }; - - let blacklisted = self.blacklist.is_user_blacklisted(user_id); - - let (user_id, full_name, user_name) = self.t_table().add_user( - sender, - local_time_date, - local_time_datetime, - count_data.name(), - blacklisted, - ); - - let chart_user = to_chart_name(user_name, &full_name, user_id); - - if !blacklisted { - self.t_chart().add_user(chart_user.clone(), user_id); - self.t_table().count_user_message( - user_id, - message, - local_time_date, - local_time_datetime, - ); - } - - let whitelisted = self.whitelist.is_user_whitelisted(user_id); - - if user_id != 0 && whitelisted && !blacklisted { - self.t_table().set_as_whitelisted(&[user_id]); - } - - let total_user = self.t_table().get_total_users_full(); - self.t_count().set_total_user(total_user as i32); - - let total_to_iter = start_from - end_at; - let message_value = 100.0 / total_to_iter as f32; - - let current_message_number = message.id(); - - // If current num = 100 and last processed = 105 - // messages with 101, 102, 103 and 104 are missing/deleted - // The current num is already getting processed so subtract 1 - let total_deleted = if last_number == -1 { - 0 - } else { - (last_number - current_message_number) - 1 - }; - - self.t_count().add_deleted_message(total_deleted); - - let total_processed = start_from - current_message_number; - let processed_percentage = if total_processed != 0 { - total_processed as f32 * message_value - } else { - message_value - }; - - self.t_count().add_one_total_message(); - if whitelisted { - self.t_count().add_one_whitelisted_message(); - self.t_count().add_whitelisted_user(user_id); - } - - // In single session set the progress by explicitly by counting it on the go - // On multi session add whatever percentage there is + new value for this session - if multi_session { - self.counter.set_session_percentage( - &count_data.name(), - processed_percentage / 100.0, - ); - } else { - self.counter - .set_bar_percentage(processed_percentage / 100.0); - } - - if !blacklisted { - self.t_chart().add_message( - local_time_datetime, - local_time_date, - chart_user, - &count_data.name(), - ); - } - if self.t_table().reload_count() > 100 { - self.t_table().create_rows(); - self.t_table().reset_reload_count(); - } - } - ProcessResult::ProcessFailed(err) => { - match err { - ProcessError::AuthorizationError => { - error!("Error acquired while trying to connect to the client"); - self.process_state = ProcessState::AuthorizationError; - } - ProcessError::FileCreationError => { - error!("Error acquired while trying to create/delete the session file"); - self.process_state = ProcessState::FileCreationFailed; - } - ProcessError::InvalidTGCode => { - error!("Invalid TG Code given for the session"); - self.process_state = ProcessState::InvalidTGCode; - } - ProcessError::NotSignedUp => { - error!("The phone number is not signed up"); - self.process_state = ProcessState::NotSignedUp; - } - ProcessError::UnknownError(e) => { - error!( - "Unknown error encountered while trying to complete the process. {e}" - ); - self.process_state = ProcessState::UnknownError; - } - ProcessError::InvalidPassword => { - error!("Invalid TG Password given for the session"); - self.process_state = ProcessState::InvalidPassword; - } - ProcessError::InvalidPhoneOrAPI(e) => { - error!( - "Possibly invalid phone number given or API keys error. Error: {e}" - ); - self.process_state = ProcessState::InvalidPhoneOrAPI; - } - ProcessError::InvalidAPIKeys => { - error!("Invalid API keys were given"); - self.process_state = ProcessState::InvalidAPIKeys; - } - ProcessError::FailedLatestMessage => { - error!("Failed to get the latest message ID"); - self.process_state = ProcessState::LatestMessageLoadingFailed; - } - } - self.go_next_or_stop(); - } - ProcessResult::LoginCodeSent(token, client) => { - info!("Login code sent to the client"); - self.stop_process(); - self.incomplete_tg_client = Some(client); - self.session.set_login_token(token); - self.process_state = ProcessState::TGCodeSent; - } - ProcessResult::PasswordRequired(token) => { - info!("Client requires a password authentication"); - self.stop_process(); - self.session.set_password_token(*token); - self.process_state = ProcessState::PasswordRequired; - } - ProcessResult::LoggedIn(name) => { - info!("Logged in to the client {name}"); - self.stop_process(); - self.session.reset_data(); - let incomplete_client = self.incomplete_tg_client.take().unwrap(); - self.tg_clients - .insert(incomplete_client.name(), incomplete_client); - self.process_state = ProcessState::LoggedIn(name); - } - ProcessResult::FloodWait => { - info!("Flood wait triggered"); - self.process_state = ProcessState::FloodWait; - } - ProcessResult::UnpackedWhitelist(chats, failed_chats) => { - for chat in chats { - let username = if let Some(name) = chat.user_chat.username() { - name.to_string() - } else { - String::from("Empty") - }; - self.whitelist.add_to_whitelist( - chat.user_chat.name().to_string(), - username, - chat.user_chat.id(), - chat.user_chat, - chat.seen_by, - ); - } - self.is_processing = false; - - self.whitelist.increase_failed_by(failed_chats); - let total_chat = self.whitelist.row_len(); - let failed_chat_num = self.whitelist.failed_whitelist_num(); - - self.process_state = - ProcessState::LoadedWhitelistedUsers(total_chat, failed_chat_num); - } - ProcessResult::UnpackedBlacklist(chats, failed_chats) => { - let mut names = Vec::new(); - let mut user_ids = Vec::new(); - - for chat in chats { - let username = if let Some(name) = chat.user_chat.username() { - name.to_string() - } else { - String::from("Empty") - }; - let full_name = chat.user_chat.name().to_string(); - let user_id = chat.user_chat.id(); - - names.push(to_chart_name(username.clone(), &full_name, user_id)); - user_ids.push(user_id); - - self.blacklist.add_to_blacklist( - full_name, - username, - user_id, - chat.user_chat, - chat.seen_by, - ); - } - self.is_processing = false; - - self.blacklist.increase_failed_by(failed_chats); - let total_chat = self.blacklist.row_len(); - let failed_chat_num = self.blacklist.failed_blacklist_num(); - - for chart in self.chart_all() { - chart.clear_blacklisted(&names); - } - - for table in self.table_all() { - table.remove_blacklisted_rows(&user_ids); - } - - self.process_state = - ProcessState::LoadedBlacklistedUsers(total_chat, failed_chat_num); - } - ProcessResult::WhiteListUser(chat) => { - self.stop_process(); - let user_id = chat.user_chat.id(); - - info!("Adding {user_id} to whitelist"); - - let username = if let Some(name) = chat.user_chat.username() { - name.to_string() - } else { - String::from("Empty") - }; - self.whitelist.add_to_whitelist( - chat.user_chat.name().to_string(), - username, - user_id, - chat.user_chat, - chat.seen_by, - ); - self.whitelist.clear_text_box(); - self.table().set_as_whitelisted(&[user_id]); - self.chart().reset_saved_bars(); - self.whitelist.save_whitelisted_users(false); - self.process_state = ProcessState::AddedToWhitelist; - } - ProcessResult::BlackListUser(chat) => { - self.stop_process(); - let user_id = chat.user_chat.id(); - - info!("Adding {user_id} to blacklist"); - - let username = if let Some(name) = chat.user_chat.username() { - name.to_string() - } else { - String::from("Empty") - }; - let full_name = chat.user_chat.name().to_string(); - let chart_name = to_chart_name(username.clone(), &full_name, user_id); - - for chart in self.chart_all() { - chart.clear_blacklisted(std::slice::from_ref(&chart_name)); - } - - for table in self.table_all() { - table.remove_blacklisted_rows(&[user_id]); - } - - self.blacklist.add_to_blacklist( - full_name, - username, - user_id, - chat.user_chat, - chat.seen_by, - ); - self.blacklist.clear_text_box(); - self.blacklist.save_blacklisted_users(false); - self.process_state = ProcessState::AddedToBlacklist; - } - ProcessResult::ChatExists(chat_name, start_at, end_at) => { - // Because we count both the start and ending message ID - let total_to_count = start_at - end_at + 1; - let total_session = self.tg_clients.len(); - let per_session_value = total_to_count / total_session as i32; - - info!("Each session to process {per_session_value}~ messages"); - - self.counter.set_session_count(total_session); - - let mut ongoing_start_at = start_at; - let mut ongoing_end_at = start_at - per_session_value; - - let mut negative_added = false; - self.cancel_count.store(false, Ordering::Relaxed); - for (index, client) in self.tg_clients.values().enumerate() { - let cancel = self.cancel_count.clone(); - self.counter.add_session(client.name()); - - let client = client.clone(); - let chat_name = chat_name.clone(); - if index == total_session - 1 { - ongoing_end_at = end_at; - } - info!( - "{} start point {} end point {}", - client.name(), - ongoing_start_at, - ongoing_end_at - ); - self.runtime.spawn(async move { - client - .start_process(ProcessStart::StartCount( - chat_name, - Some(ongoing_start_at), - Some(ongoing_end_at), - true, - cancel, - )) - .await; - }); - ongoing_start_at -= per_session_value; - ongoing_end_at -= per_session_value; - - // because we count both starting and end point - // Example starting point 100, end point 1. Total session 4, per session to process 25 messages - // First session start at 100 end at 100 - 25 = 75 - // Next session start at (last session start - per session process) end at (last session end - per session process) - // - // Here start at would be 75 which will overlap a message so reduce 1 - // - // next session start at 49 end at 25 and so on - if !negative_added { - ongoing_start_at -= 1; - negative_added = true; - } - } - } - } - true - } else { - false - } - } - - pub fn stop_process(&mut self) { - self.is_processing = false; - self.counter.counting_ended(); - } - - fn go_next_or_stop(&mut self) { - if self.counter.counting() { - self.counter.increment_ongoing(); - self.process_next_count(); - } else { - self.stop_process(); - } - } -} diff --git a/src/ui_components/tab_ui/blacklist.rs b/src/ui_components/tab_ui/blacklist.rs deleted file mode 100644 index da0b08b..0000000 --- a/src/ui_components/tab_ui/blacklist.rs +++ /dev/null @@ -1,436 +0,0 @@ -use eframe::egui::scroll_area::DragScroll; -use eframe::egui::{Align, Button, Grid, Label, Layout, Response, RichText, Sense, TextEdit, Ui}; -use egui_extras::Column; -use egui_selectable_table::{ - ColumnOperations, ColumnOrdering, SelectableRow, SelectableTable, SortOrder, -}; -use grammers_client::types::Chat; -use log::{error, info}; -use std::collections::HashSet; - -use crate::tg_handler::ProcessStart; -use crate::ui_components::MainWindow; -use crate::ui_components::processor::{ColumnName, PackedBlacklistedUser, ProcessState}; -use crate::utils::{get_blacklisted, save_blacklisted_users, separate_blacklist_by_seen}; - -#[derive(Default)] -struct Config { - deleted_selected: bool, -} - -impl ColumnOperations for ColumnName { - fn column_text(&self, row: &BlackListRowData) -> String { - match self { - ColumnName::Name => row.name.clone(), - ColumnName::Username => row.username.clone(), - ColumnName::UserID => row.id.to_string(), - _ => unreachable!(), - } - } - fn create_header( - &self, - ui: &mut eframe::egui::Ui, - _sort_order: Option, - _table: &mut SelectableTable, - ) -> Option { - let label_text = self.to_string(); - let hover_text = match self { - ColumnName::Name => "Telegram name of the user".to_string(), - ColumnName::Username => "Telegram username of the user".to_string(), - - ColumnName::UserID => "Telegram User ID of the user".to_string(), - _ => unreachable!(), - }; - - let label_text = RichText::new(label_text).strong(); - - let response = ui - .add_sized(ui.available_size(), Label::new(label_text)) - .on_hover_text(hover_text); - - Some(response) - } - fn create_table_row( - &self, - ui: &mut Ui, - row: &SelectableRow, - column_selected: bool, - table: &mut SelectableTable, - ) -> Response { - let row_data = &row.row_data; - let mut show_tooltip = false; - let row_text = match self { - ColumnName::Name => { - show_tooltip = true; - row_data.name.clone() - } - ColumnName::Username => { - show_tooltip = true; - row_data.username.clone() - } - ColumnName::UserID => row_data.id.to_string(), - _ => unreachable!(), - }; - let is_selected = column_selected; - - let mut label = ui - .add_sized( - ui.available_size(), - Button::selectable(is_selected, &row_text), - ) - .interact(Sense::drag()); - - if show_tooltip { - label = label.on_hover_text(row_text); - } - label.context_menu(|ui| { - if ui.button("Deleted Selected").clicked() { - table.config.deleted_selected = true; - ui.close(); - } - }); - label - } -} - -impl ColumnOrdering for ColumnName { - fn order_by(&self, row_1: &BlackListRowData, row_2: &BlackListRowData) -> std::cmp::Ordering { - row_1.name.cmp(&row_2.name) - } -} -#[derive(Clone)] -struct BlackListRowData { - name: String, - username: String, - id: i64, - belongs_to: Chat, - seen_by: String, -} - -impl BlackListRowData { - fn new(name: String, username: String, id: i64, belongs_to: Chat, seen_by: String) -> Self { - BlackListRowData { - name, - username, - id, - belongs_to, - seen_by, - } - } -} - -pub struct BlacklistData { - table: SelectableTable, - target_username: String, - failed_blacklist: i32, - all_ids: HashSet, - search_query: String, -} -impl Default for BlacklistData { - fn default() -> Self { - let table = SelectableTable::new(vec![ - ColumnName::Name, - ColumnName::Username, - ColumnName::UserID, - ]) - .auto_scroll() - .select_full_row() - .serial_column() - .no_ctrl_a_capture() - .auto_reload(1); - - Self { - table, - target_username: String::new(), - failed_blacklist: 0, - all_ids: HashSet::new(), - search_query: String::new(), - } - } -} - -impl BlacklistData { - /// Add a new row to the UI - pub fn add_to_blacklist( - &mut self, - name: String, - username: String, - id: i64, - belongs_to: Chat, - seen_by: String, - ) { - let name = if name.is_empty() { - String::from("Deleted Account") - } else { - name - }; - - info!("Adding {name} to blacklist, seen by {seen_by}"); - self.all_ids.insert(id); - self.table.add_modify_row(|_rows| { - let to_add = BlackListRowData::new(name, username, id, belongs_to, seen_by); - Some(to_add) - }); - } - - /// Check if user is blacklisted/in the blacklist UI - pub fn is_user_blacklisted(&self, id: i64) -> bool { - self.all_ids.contains(&id) - } - - /// Save the current row data in the blacklist json - pub fn save_blacklisted_users(&self, overwrite: bool) { - let mut packed_chats = Vec::new(); - - self.table.get_all_rows().iter().for_each(|(_id, row)| { - let hex_value = row.row_data.belongs_to.pack().to_hex(); - packed_chats.push(PackedBlacklistedUser::new( - hex_value, - row.row_data.seen_by.clone(), - )); - }); - - save_blacklisted_users(packed_chats, overwrite); - } - - /// Removes selected row from blacklist and saves the result - fn remove_selected(&mut self) -> Vec { - let active_rows = self.table.get_selected_rows(); - - let mut row_ids = Vec::new(); - for i in &active_rows { - info!( - "Removing user {} | {} from blacklist", - i.row_data.username, i.row_data.id - ); - self.all_ids.remove(&i.row_data.id); - self.table.add_modify_row(|rows| { - rows.remove(&i.id); - row_ids.push(i.row_data.id); - None - }); - } - self.save_blacklisted_users(true); - row_ids - } - - /// Removes all row from blacklist and saves the result - fn remove_all(&mut self) -> Vec { - info!("Removing all users from blacklist"); - let row_keys = self.all_ids.iter().copied().collect(); - self.table.clear_all_rows(); - self.save_blacklisted_users(true); - self.all_ids.clear(); - - row_keys - } - - pub fn clear_text_box(&mut self) { - self.target_username.clear(); - } - - pub fn increase_failed_by(&mut self, count: i32) { - self.failed_blacklist += count; - } - - pub fn row_len(&self) -> usize { - self.table.total_rows() - } - - pub fn failed_blacklist_num(&self) -> i32 { - self.failed_blacklist - } -} - -impl MainWindow { - pub fn show_blacklist_ui(&mut self, ui: &mut Ui) { - if self.blacklist.table.config.deleted_selected { - self.blacklist.table.config.deleted_selected = false; - let deleted = self.blacklist.remove_selected(); - let total_to_remove = deleted.len(); - self.process_state = ProcessState::BlacklistedUserRemoved(total_to_remove); - } - - Grid::new("blacklist Grid") - .num_columns(2) - .spacing([5.0, 10.0]) - .show(ui, |ui| { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("Target Username:")); - }); - ui.add_sized( - ui.available_size(), - TextEdit::singleline(&mut self.blacklist.target_username) - .hint_text("Telegram username: @username"), - ) - .on_hover_text( - "Don't have a username? - -Use the Counter to count at least 1 message by that user -then right click on User Table to blacklist", - ); - }); - - ui.vertical_centered(|ui| { - ui.add_space(10.0); - let button = if self.is_processing || self.blacklist.target_username.is_empty() { - ui.add_enabled(false, Button::new("Add to blacklist")) - } else { - ui.button("Add to blacklist") - } - .on_hover_text("Add the username to blacklist"); - - if button.clicked() { - self.blacklist_new_user(); - } - }); - - ui.add_space(20.0); - - ui.horizontal(|ui| { - let text_box = TextEdit::singleline(&mut self.blacklist.search_query) - .hint_text("Search by name, username or user ID"); - ui.add(text_box); - - if ui - .button("Search") - .on_hover_text("Filter rows that match the search query") - .clicked() - { - let search_query = self.blacklist.search_query.clone(); - - if search_query.is_empty() { - self.blacklist.table.recreate_rows(); - self.blacklist.search_query.clear(); - } else { - let column_list = vec![ColumnName::Name, ColumnName::Username, ColumnName::UserID]; - - self.blacklist - .table - .search_and_show(&column_list, &search_query, None, None); - } - - } - if ui - .button("Clear") - .on_hover_text("Clear search result") - .clicked() - { - self.blacklist.table.recreate_rows(); - self.blacklist.search_query.clear(); - } - - ui.separator(); - - - if ui - .button("Select All") - .on_hover_text("Select all users. Also usable with CTRL + A. Use CTRL + mouse click for manual selection") - .clicked() - { - self.blacklist.table.select_all(); - } - if ui - .button("Delete Selected") - .on_hover_text("Delete selected users from blacklist") - .clicked() - { - let deleted = self.blacklist.remove_selected(); - let total_to_remove = deleted.len(); - self.process_state = ProcessState::BlacklistedUserRemoved(total_to_remove); - } - if ui - .button("Delete All") - .on_hover_text("Delete all blacklisted users") - .clicked() - { - let _ = self.blacklist.remove_all(); - self.process_state = ProcessState::AllBlacklistRemoved; - } - }); - - ui.separator(); - - let column_size = (ui.available_width() - 20.0) / 3.0; - self.blacklist.table.show_ui(ui, |table| { - table - .striped(true) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::exact(column_size).clip(true)) - .column(Column::exact(column_size)) - .column(Column::exact(column_size)) - .drag_to_scroll(DragScroll::Never) - .auto_shrink([false; 2]) - .min_scrolled_height(0.0) - }); - } - - pub fn load_blacklisted_users(&mut self) { - // This function will never be called if there are no sessions detected. - // Unnecessary to handle in case `self.tg_clients` is empty - - let all_blacklisted_users = get_blacklisted(); - - if all_blacklisted_users.is_err() { - // This case means it failed to deserialize the json or is using the old blacklist json format - // All previous data will be removed - error!("Failed to deserialize the blacklist users json file. Deleting saved json data"); - save_blacklisted_users(Vec::new(), true); - self.process_state = ProcessState::FailedLoadBlacklistedUsers; - self.is_processing = false; - return; - } - - // separate blacklist data by seen_by as the key and hex as the value - let separated_data = separate_blacklist_by_seen(all_blacklisted_users.unwrap()); - - if separated_data.is_empty() { - self.is_processing = false; - return; - } - - // Open a thread for each unique session found in the blacklist json and pass the relevant hex data to that thread - // `hex_data` cannot be empty as the key will only exist if there is at least one hex found - for (seen_by, hex_data) in separated_data { - let client = self.tg_clients.get(&seen_by); - - let Some(tg_client) = client.cloned() else { - let total_blacklist = hex_data.len(); - error!( - "{seen_by} client does not exist! Ignoring {total_blacklist} blacklisted users" - ); - self.blacklist.increase_failed_by(total_blacklist as i32); - - let success_blacklist = self.blacklist.row_len(); - let failed_blacklist = self.blacklist.failed_blacklist_num(); - self.process_state = - ProcessState::LoadedBlacklistedUsers(success_blacklist, failed_blacklist); - continue; - }; - self.runtime.spawn(async { - tg_client - .start_process(ProcessStart::LoadBlacklistedUsers(hex_data)) - .await; - }); - } - } - - pub fn blacklist_new_user(&mut self) { - let selected_session = self.get_selected_session(); - - if selected_session.is_empty() { - self.process_state = ProcessState::EmptySelectedSession; - return; - } - - let client = self.tg_clients.get(&selected_session).unwrap().clone(); - let target_username = self.blacklist.target_username.clone().replace('@', ""); - self.is_processing = true; - - self.runtime.spawn(async { - client - .start_process(ProcessStart::NewBlacklistUser(target_username)) - .await; - }); - } -} diff --git a/src/ui_components/tab_ui/mod.rs b/src/ui_components/tab_ui/mod.rs deleted file mode 100644 index ba6cc70..0000000 --- a/src/ui_components/tab_ui/mod.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod blacklist; -mod charts; -mod counter; -mod session; -mod user_table; -mod whitelist; - -pub use blacklist::*; -pub use charts::*; -pub use counter::*; -pub use session::*; -pub use user_table::*; -pub use whitelist::*; diff --git a/src/ui_components/tab_ui/session.rs b/src/ui_components/tab_ui/session.rs deleted file mode 100644 index 9b94d19..0000000 --- a/src/ui_components/tab_ui/session.rs +++ /dev/null @@ -1,275 +0,0 @@ -use eframe::egui::{Align, Button, Checkbox, Context, Grid, Label, Layout, TextEdit, Ui, vec2}; -use grammers_client::types::{LoginToken, PasswordToken}; -use std::sync::Arc; -use tokio::sync::Mutex; - -use crate::tg_handler::{NewProcess, ProcessStart, start_process}; -use crate::ui_components::MainWindow; -use crate::ui_components::processor::ProcessState; - -#[derive(Default)] -pub struct SessionData { - session_name: String, - phone_number: String, - tg_code: String, - tg_password: String, - is_temporary: bool, - password_token: Option>>, - tg_code_token: Option>>, -} - -impl SessionData { - fn get_session_name(&self) -> String { - self.session_name.clone() - } - - fn get_phone_number(&self) -> String { - self.phone_number.replace('+', "") - } - - fn get_password(&self) -> String { - self.tg_password.clone() - } - - fn get_is_temporary(&self) -> bool { - self.is_temporary - } - - pub fn set_login_token(&mut self, token: LoginToken) { - self.tg_code_token = Some(Arc::new(Mutex::new(token))); - } - - pub fn set_password_token(&mut self, token: PasswordToken) { - self.password_token = Some(Arc::new(Mutex::new(token))); - } - - fn get_tg_code(&self) -> String { - self.tg_code.clone() - } - - fn get_tg_code_token(&self) -> Arc> { - self.tg_code_token.clone().unwrap() - } - - fn get_password_token(&self) -> Arc> { - self.password_token.clone().unwrap() - } - - pub fn reset_data(&mut self) { - self.session_name = String::new(); - self.phone_number = String::new(); - self.tg_code = String::new(); - self.tg_password = String::new(); - self.is_temporary = false; - self.password_token = None; - self.tg_code_token = None; - } -} - -impl MainWindow { - pub fn show_session_ui(&mut self, ui: &mut Ui) { - Grid::new("Session Grid") - .num_columns(2) - .spacing([5.0, 10.0]) - .show(ui, |ui| { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("Session Name:")); - }); - let text_edit = TextEdit::singleline(&mut self.session.session_name) - .hint_text("My TG Session Name"); - if self.session.tg_code_token.is_some() || self.session.password_token.is_some() { - ui.add_enabled(false, text_edit.min_size(ui.available_size())); - } else { - let hover_text = if self.session.is_temporary { - "A name for the temporary session" - } else { - "Save the session in a file with this name for later access" - }; - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add_sized(ui.available_size(), text_edit) - .on_hover_text(hover_text); - }); - } - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("Phone Number:")); - }); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let text_edit = TextEdit::singleline(&mut self.session.phone_number) - .hint_text("International format: +1234567890"); - if self.session.password_token.is_some() || self.session.tg_code_token.is_some() - { - ui.add_enabled(false, text_edit.min_size(ui.available_size())); - } else { - ui.add_sized(ui.available_size(), text_edit).on_hover_text( - "The phone number of your Telegram in international format", - ); - } - }); - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("Login Code:")); - }); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let button = Button::new("Send Code"); - if self.session.phone_number.is_empty() - || self.session.password_token.is_some() - || self.session.session_name.is_empty() - || self.is_processing - { - ui.add_enabled(false, button); - } else if ui - .add(button) - .on_hover_text("Send the code to login to the account") - .clicked() - { - self.request_login_code(ui.ctx().clone()); - } - - let text_edit = - TextEdit::singleline(&mut self.session.tg_code).hint_text("12345"); - if self.session.tg_code_token.is_some() { - ui.add_sized(ui.available_size(), text_edit).on_hover_text( - "The Telegram login code either sent to TG or to the phone number", - ); - } else { - ui.add_enabled(false, text_edit.min_size(ui.available_size())); - } - }); - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("Login Password:")); - }); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let text_edit = TextEdit::singleline(&mut self.session.tg_password) - .password(true) - .hint_text("Your Telegram login password"); - if self.session.password_token.is_some() { - ui.add_sized(ui.available_size(), text_edit) - .on_hover_text("Telegram login password"); - } else { - ui.add_enabled(false, text_edit.min_size(ui.available_size())); - } - }); - - ui.end_row(); - - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("Temporary:")); - }); - ui.with_layout(Layout::left_to_right(Align::Center), |ui| { - if self.session.tg_code_token.is_some() || self.is_processing { - ui.add_enabled( - false, - Checkbox::new( - &mut self.session.is_temporary, - "Do not create a session file", - ), - ); - } else { - ui.checkbox( - &mut self.session.is_temporary, - "Do not create a session file", - ) - .on_hover_text( - "Create a new temporary session? -If yes, it will try to log out before the app is closed and no session file will be created", - ); - } - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if ui - .button("Reset Session") - .on_hover_text("Reset and clear new session creation data") - .clicked() - { - self.session.reset_data(); - self.incomplete_tg_client = None; - } - }) - }); - }); - - ui.add_space(40.0); - - ui.vertical_centered(|ui| { - let button = Button::new("Create Session").min_size(vec2(100.0, 40.0)); - if self.is_processing - || self.session.phone_number.is_empty() - || self.session.session_name.is_empty() - || self.session.tg_code.is_empty() - || (self.session.password_token.is_some() && self.session.tg_password.is_empty()) - { - ui.add_enabled(false, button); - } else if ui - .add(button) - .on_hover_text("Try to create a new session with the Telegram login info") - .clicked() - { - if self.session.password_token.is_some() { - self.sign_in_password(); - } else { - self.sign_in_code(); - } - } - }); - } - - /// Starts a thread to send a Telegram login code to the phone number - fn request_login_code(&mut self, context: Context) { - let phone_num = self.session.get_phone_number(); - let session_name = self.session.get_session_name(); - let is_temporary = self.session.get_is_temporary(); - - let sender_clone = self.tg_sender.clone(); - - self.is_processing = true; - self.process_state = ProcessState::SendingTGCode; - - self.runtime.spawn(async move { - start_process( - NewProcess::SendLoginCode(session_name, phone_num, is_temporary), - sender_clone, - context, - ) - .await; - }); - } - - /// Starts a thread to try to log in with the given login code - fn sign_in_code(&mut self) { - self.is_processing = true; - self.process_state = ProcessState::LogInWithCode; - - let code = self.session.get_tg_code(); - let token = self.session.get_tg_code_token(); - - let client = self.incomplete_tg_client.clone().unwrap(); - self.runtime.spawn(async move { - client - .start_process(ProcessStart::SignInCode(token, code)) - .await; - }); - } - - /// Starts a thread to try to log in with the given login password - fn sign_in_password(&mut self) { - self.is_processing = true; - self.process_state = ProcessState::LogInWithPassword; - - let password = self.session.get_password(); - let token = self.session.get_password_token(); - - let client = self.incomplete_tg_client.clone().unwrap(); - self.runtime.spawn(async move { - client - .start_process(ProcessStart::SignInPasswords(token, password)) - .await; - }); - } -} diff --git a/src/ui_components/tab_ui/whitelist.rs b/src/ui_components/tab_ui/whitelist.rs deleted file mode 100644 index 5e52f9d..0000000 --- a/src/ui_components/tab_ui/whitelist.rs +++ /dev/null @@ -1,445 +0,0 @@ -use eframe::egui::scroll_area::DragScroll; -use eframe::egui::{Align, Button, Grid, Label, Layout, Response, RichText, Sense, TextEdit, Ui}; -use egui_extras::Column; -use egui_selectable_table::{ - ColumnOperations, ColumnOrdering, SelectableRow, SelectableTable, SortOrder, -}; -use grammers_client::types::Chat; -use log::{error, info}; -use std::collections::HashSet; - -use crate::tg_handler::ProcessStart; -use crate::ui_components::MainWindow; -use crate::ui_components::processor::{ColumnName, PackedWhitelistedUser, ProcessState}; -use crate::utils::{get_whitelisted, save_whitelisted_users, separate_whitelist_by_seen}; - -#[derive(Default)] -struct Config { - deleted_selected: bool, -} - -impl ColumnOperations for ColumnName { - fn column_text(&self, row: &WhiteListRowData) -> String { - match self { - ColumnName::Name => row.name.clone(), - ColumnName::Username => row.username.clone(), - ColumnName::UserID => row.id.to_string(), - _ => unreachable!(), - } - } - fn create_header( - &self, - ui: &mut eframe::egui::Ui, - _sort_order: Option, - _table: &mut SelectableTable, - ) -> Option { - let label_text = self.to_string(); - let hover_text = match self { - ColumnName::Name => "Telegram name of the user".to_string(), - ColumnName::Username => "Telegram username of the user".to_string(), - - ColumnName::UserID => "Telegram User ID of the user".to_string(), - _ => unreachable!(), - }; - - let label_text = RichText::new(label_text).strong(); - - let response = ui - .add_sized(ui.available_size(), Label::new(label_text)) - .on_hover_text(hover_text); - - Some(response) - } - fn create_table_row( - &self, - ui: &mut Ui, - row: &SelectableRow, - column_selected: bool, - table: &mut SelectableTable, - ) -> Response { - let row_data = &row.row_data; - let mut show_tooltip = false; - let row_text = match self { - ColumnName::Name => { - show_tooltip = true; - row_data.name.clone() - } - ColumnName::Username => { - show_tooltip = true; - row_data.username.clone() - } - ColumnName::UserID => row_data.id.to_string(), - _ => unreachable!(), - }; - let is_selected = column_selected; - - let mut label = ui - .add_sized( - ui.available_size(), - Button::selectable(is_selected, &row_text), - ) - .interact(Sense::drag()); - - if show_tooltip { - label = label.on_hover_text(row_text); - } - label.context_menu(|ui| { - if ui.button("Deleted Selected").clicked() { - table.config.deleted_selected = true; - ui.close(); - } - }); - label - } -} - -impl ColumnOrdering for ColumnName { - fn order_by(&self, row_1: &WhiteListRowData, row_2: &WhiteListRowData) -> std::cmp::Ordering { - row_1.name.cmp(&row_2.name) - } -} - -#[derive(Clone)] -struct WhiteListRowData { - name: String, - username: String, - id: i64, - belongs_to: Chat, - seen_by: String, -} - -impl WhiteListRowData { - fn new(name: String, username: String, id: i64, belongs_to: Chat, seen_by: String) -> Self { - WhiteListRowData { - name, - username, - id, - belongs_to, - seen_by, - } - } -} - -pub struct WhitelistData { - table: SelectableTable, - target_username: String, - failed_whitelist: i32, - all_ids: HashSet, - search_query: String, -} - -impl Default for WhitelistData { - fn default() -> Self { - let table = SelectableTable::new(vec![ - ColumnName::Name, - ColumnName::Username, - ColumnName::UserID, - ]) - .auto_scroll() - .select_full_row() - .serial_column() - .no_ctrl_a_capture() - .auto_reload(1); - Self { - table, - target_username: String::new(), - failed_whitelist: 0, - all_ids: HashSet::new(), - search_query: String::new(), - } - } -} - -impl WhitelistData { - /// Add a new row to the UI - pub fn add_to_whitelist( - &mut self, - name: String, - username: String, - id: i64, - belongs_to: Chat, - seen_by: String, - ) { - let name = if name.is_empty() { - String::from("Deleted Account") - } else { - name - }; - - info!("Adding {name} to whitelist, seen by {seen_by}"); - self.all_ids.insert(id); - self.table.add_modify_row(|_rows| { - let to_add = WhiteListRowData::new(name, username, id, belongs_to, seen_by); - Some(to_add) - }); - } - - /// Check if user is whitelisted/in the whitelist UI - pub fn is_user_whitelisted(&self, id: i64) -> bool { - self.all_ids.contains(&id) - } - - /// Save the current row data in the whitelist json - pub fn save_whitelisted_users(&self, overwrite: bool) { - let mut packed_chats = Vec::new(); - - self.table.get_all_rows().iter().for_each(|(_id, row)| { - let hex_value = row.row_data.belongs_to.pack().to_hex(); - packed_chats.push(PackedWhitelistedUser::new( - hex_value, - row.row_data.seen_by.clone(), - )); - }); - - save_whitelisted_users(packed_chats, overwrite); - } - - /// Removes selected row from whitelist and saves the result - fn remove_selected(&mut self) -> Vec { - let active_rows = self.table.get_selected_rows(); - - let mut row_ids = Vec::new(); - for i in &active_rows { - info!( - "Removing user {} | {} from whitelist", - i.row_data.username, i.row_data.id - ); - self.all_ids.remove(&i.row_data.id); - self.table.add_modify_row(|rows| { - rows.remove(&i.id); - row_ids.push(i.row_data.id); - None - }); - } - self.save_whitelisted_users(true); - row_ids - } - - /// Removes all row from whitelist and saves the result - fn remove_all(&mut self) -> Vec { - info!("Removing all users from whitelist"); - let row_keys = self.all_ids.iter().copied().collect(); - self.table.clear_all_rows(); - self.save_whitelisted_users(true); - self.all_ids.clear(); - - row_keys - } - - pub fn clear_text_box(&mut self) { - self.target_username.clear(); - } - - pub fn increase_failed_by(&mut self, count: i32) { - self.failed_whitelist += count; - } - - pub fn row_len(&self) -> usize { - self.table.total_rows() - } - - pub fn failed_whitelist_num(&self) -> i32 { - self.failed_whitelist - } -} - -impl MainWindow { - pub fn show_whitelist_ui(&mut self, ui: &mut Ui) { - if self.whitelist.table.config.deleted_selected { - self.whitelist.table.config.deleted_selected = false; - let rows = self.whitelist.table.get_selected_rows(); - let total_to_remove = rows.len(); - let deleted_ids: Vec = rows.iter().map(|row| row.row_data.id).collect(); - - self.table().remove_whitelist(&deleted_ids); - self.whitelist.remove_selected(); - self.process_state = ProcessState::WhitelistedUserRemoved(total_to_remove); - } - - Grid::new("Whitelist Grid") - .num_columns(2) - .spacing([5.0, 10.0]) - .show(ui, |ui| { - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add(Label::new("Target Username:")); - }); - ui.add_sized( - ui.available_size(), - TextEdit::singleline(&mut self.whitelist.target_username) - .hint_text("Telegram username: @username"), - ) - .on_hover_text( - "Don't have a username? - -Use the Counter to count at least 1 message by that user -then right click on User Table to whitelist", - ); - }); - - ui.vertical_centered(|ui| { - ui.add_space(10.0); - let button = if self.is_processing || self.whitelist.target_username.is_empty() { - ui.add_enabled(false, Button::new("Add to whitelist")) - } else { - ui.button("Add to whitelist") - } - .on_hover_text("Add the username to whitelist"); - - if button.clicked() { - self.whitelist_new_user(); - } - }); - - ui.add_space(20.0); - - let column_size = (ui.available_width() - 20.0) / 3.0; - - ui.horizontal(|ui| { - let text_box = TextEdit::singleline(&mut self.whitelist.search_query) - .hint_text("Search by name, username or user ID"); - ui.add(text_box); - - if ui - .button("Search") - .on_hover_text("Filter rows that match the search query") - .clicked() - { - let search_query = self.whitelist.search_query.clone(); - - if search_query.is_empty() { - self.whitelist.table.recreate_rows(); - self.whitelist.search_query.clear(); - } else { - let column_list = vec![ColumnName::Name, ColumnName::Username, ColumnName::UserID]; - - self.whitelist - .table - .search_and_show(&column_list, &search_query, None, None); - } - } - if ui - .button("Clear") - .on_hover_text("Clear search result") - .clicked() - { - self.whitelist.table.recreate_rows(); - self.whitelist.search_query.clear(); - } - - ui.separator(); - - if ui - .button("Select All") - .on_hover_text("Select all users. Also usable with CTRL + A. Use CTRL + mouse click for manual selection") - .clicked() - { - self.whitelist.table.select_all(); - } - if ui - .button("Delete Selected") - .on_hover_text("Delete selected users from whitelist") - .clicked() - { - let deleted: Vec = self.whitelist.remove_selected(); - let total_to_remove = deleted.len(); - - self.table().remove_whitelist(&deleted); - self.chart().reset_saved_bars(); - self.process_state = ProcessState::WhitelistedUserRemoved(total_to_remove); - } - if ui - .button("Delete All") - .on_hover_text("Delete all whitelisted users") - .clicked() - { - let deleted = self.whitelist.remove_all(); - - self.table().remove_whitelist(&deleted); - self.chart().reset_saved_bars(); - self.process_state = ProcessState::AllWhitelistRemoved; - } - }); - - ui.separator(); - self.whitelist.table.show_ui(ui, |table| { - table - .striped(true) - .cell_layout(Layout::left_to_right(Align::Center)) - .column(Column::exact(column_size).clip(true)) - .column(Column::exact(column_size)) - .column(Column::exact(column_size)) - .drag_to_scroll(DragScroll::Never) - .auto_shrink([false; 2]) - .min_scrolled_height(0.0) - }); - } - - pub fn load_whitelisted_users(&mut self) { - // This function will never be called if there are no sessions detected. - // Unnecessary to handle in case `self.tg_clients` is empty - - let all_whitelisted_users = get_whitelisted(); - - if all_whitelisted_users.is_err() { - // This case means it failed to deserialize the json or is using the old whitelist json format - // All previous data will be removed - error!("Failed to deserialize a whitelist users json file. Deleting saved json data"); - self.whitelist.save_whitelisted_users(true); - self.process_state = ProcessState::FailedLoadWhitelistedUsers; - self.is_processing = false; - return; - } - - // separate whitelist data by seen_by as the key and hex as the value - let separated_data = separate_whitelist_by_seen(all_whitelisted_users.unwrap()); - - if separated_data.is_empty() { - self.is_processing = false; - return; - } - - // Open a thread for each unique session found in the whitelist json and pass the relevant hex data to that thread - // `hex_data` cannot be empty as the key will only exist if there is at least one hex found - for (seen_by, hex_data) in separated_data { - let client = self.tg_clients.get(&seen_by); - - let Some(tg_client) = client.cloned() else { - let total_whitelist = hex_data.len(); - error!( - "{seen_by} client does not exist! Ignoring {total_whitelist} whitelisted users" - ); - self.whitelist.increase_failed_by(total_whitelist as i32); - - let success_whitelist = self.whitelist.row_len(); - let failed_whitelist = self.whitelist.failed_whitelist_num(); - self.process_state = - ProcessState::LoadedWhitelistedUsers(success_whitelist, failed_whitelist); - continue; - }; - self.runtime.spawn(async move { - tg_client - .start_process(ProcessStart::LoadWhitelistedUsers(hex_data)) - .await; - }); - } - } - - pub fn whitelist_new_user(&mut self) { - let selected_session = self.get_selected_session(); - - if selected_session.is_empty() { - self.process_state = ProcessState::EmptySelectedSession; - return; - } - - let client = self.tg_clients.get(&selected_session).unwrap().clone(); - let target_username = self.whitelist.target_username.clone().replace('@', ""); - self.is_processing = true; - - self.runtime.spawn(async move { - client - .start_process(ProcessStart::NewWhitelistUser(target_username)) - .await; - }); - } -} diff --git a/src/ui_components/widgets/animated_label.rs b/src/ui_components/widgets/animated_label.rs deleted file mode 100644 index 1cc64fc..0000000 --- a/src/ui_components/widgets/animated_label.rs +++ /dev/null @@ -1,166 +0,0 @@ -use eframe::egui::{ - CornerRadius, Id, LayerId, Order, Response, Role, Sense, Stroke, StrokeKind, TextStyle, Ui, - Vec2, Widget, WidgetInfo, WidgetText, -}; -use eframe::emath::GuiRounding; - -pub struct AnimatedLabel { - text: WidgetText, - selected: bool, - selected_position: Id, - hover_position: Id, - x_size: f32, - y_size: f32, - rounding: Option, - separator_position: (bool, bool), -} - -#[allow(clippy::too_many_arguments)] -impl AnimatedLabel { - pub fn new( - selected: bool, - text: impl Into, - selected_position: Id, - hover_position: Id, - x_size: f32, - y_size: f32, - rounding: Option, - separator_position: (bool, bool), - ) -> Self { - Self { - selected, - text: text.into(), - selected_position, - hover_position, - x_size, - y_size, - rounding, - separator_position, - } - } -} - -impl Widget for AnimatedLabel { - fn ui(self, ui: &mut Ui) -> Response { - let Self { - selected, - text, - selected_position, - hover_position, - x_size, - y_size, - rounding, - separator_position, - } = self; - - let ui_spacing = ui.spacing().item_spacing.x; - ui.spacing_mut().item_spacing.x = 0.0; - - let (separator_left, separator_right) = separator_position; - let button_padding = ui.spacing().button_padding; - - let desired_size = Vec2::new(x_size, y_size); - let (rect, response) = ui.allocate_exact_size(desired_size, Sense::click()); - - response.widget_info(|| { - WidgetInfo::selected(Role::Button, ui.is_enabled(), selected, text.text()) - }); - - if ui.is_rect_visible(response.rect) { - let visuals = ui.style().interact_selectable(&response, selected); - let rounding = rounding.unwrap_or(visuals.corner_radius); - - let expanded_rect = rect.expand(visuals.expansion); - - let painter = ui.painter(); - let y1 = expanded_rect - .min - .y - .round_to_pixels(painter.pixels_per_point()); - - let y2 = expanded_rect - .max - .y - .round_to_pixels(painter.pixels_per_point()); - - if separator_left { - let painter = ui.painter(); - let fixed_line_x = painter.round_to_pixel_center(rect.left()); - let color = ui.visuals().widgets.noninteractive.fg_stroke.color; - let stroke = Stroke::new(1.0, color); - painter.vline(fixed_line_x, y1..=y2, stroke); - } - - let text_galley = ui.painter().layout_no_wrap( - text.text().to_string(), - TextStyle::Button.resolve(ui.style()), - visuals.text_color(), - ); - - let text_pos = ui - .layout() - .align_size_within_rect(text_galley.size(), rect.shrink2(button_padding)) - .min; - - let mut background_rect = expanded_rect; - - if !separator_left && !separator_right { - let y_difference = background_rect.height(); - let remaining = y_size - y_difference; - background_rect.min.y -= remaining / 2.0; - background_rect.max.y += remaining / 2.0; - } - - let half_x_size = x_size / 2.0; - - if selected { - let x_selected = - ui.ctx() - .animate_value_with_time(selected_position, rect.center().x, 0.5); - background_rect.min.x = x_selected - half_x_size + 0.5; - background_rect.max.x = x_selected + half_x_size - 0.5; - - ui.painter().rect( - background_rect, - rounding, - visuals.weak_bg_fill, - visuals.bg_stroke, - StrokeKind::Inside, - ); - } - - if response.highlighted() || response.has_focus() || response.hovered() { - let x_hover = - ui.ctx() - .animate_value_with_time(hover_position, rect.center().x, 0.5); - background_rect.min.x = x_hover - half_x_size + 0.5; - background_rect.max.x = x_hover + half_x_size - 0.5; - - ui.painter().rect( - background_rect, - rounding, - visuals.weak_bg_fill, - visuals.bg_stroke, - StrokeKind::Inside, - ); - } - - ui.painter() - .clone() - .with_layer_id(LayerId::new(Order::Background, Id::unique("text_layer"))) - .galley(text_pos, text_galley, visuals.text_color()); - - if separator_right { - let painter = ui.painter(); - let fixed_line_x = painter.round_to_pixel_center(rect.right()); - let color = ui.visuals().widgets.noninteractive.fg_stroke.color; - let stroke = Stroke::new(1.0, color); - painter.vline(fixed_line_x, y1..=y2, stroke); - } - } - - ui.spacing_mut().item_spacing.x = ui_spacing; - - response - } -} diff --git a/src/ui_components/widgets/mod.rs b/src/ui_components/widgets/mod.rs deleted file mode 100644 index c0e5180..0000000 --- a/src/ui_components/widgets/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod animated_label; -mod row_label; - -pub use animated_label::*; -pub use row_label::*; diff --git a/src/ui_components/widgets/row_label.rs b/src/ui_components/widgets/row_label.rs deleted file mode 100644 index e631331..0000000 --- a/src/ui_components/widgets/row_label.rs +++ /dev/null @@ -1,99 +0,0 @@ -use eframe::egui::{ - Response, Role, Sense, StrokeKind, TextStyle, Ui, Widget, WidgetInfo, WidgetText, -}; -use eframe::emath::NumExt; -use eframe::epaint::Color32; - -/// Copy of `SelectableLabel` source with minor modifications -pub struct RowLabel { - text: WidgetText, - selected: bool, - whitelisted: bool, -} - -impl RowLabel { - pub fn new(selected: bool, whitelisted: bool, text: impl Into) -> Self { - Self { - selected, - text: text.into(), - whitelisted, - } - } -} - -impl Widget for RowLabel { - fn ui(self, ui: &mut Ui) -> Response { - let Self { - selected, - text, - whitelisted, - } = self; - let button_padding = ui.spacing().button_padding; - let total_extra = button_padding + button_padding; - - let wrap_width = ui.available_width() - total_extra.x; - let text = text.into_galley(ui, None, wrap_width, TextStyle::Button); - - let mut desired_size = total_extra + text.size(); - desired_size.y = desired_size.y.at_least(ui.spacing().interact_size.y); - let (rect, response) = ui.allocate_at_least(desired_size, Sense::click()); - response.widget_info(|| { - WidgetInfo::selected(Role::Button, ui.is_enabled(), selected, text.text()) - }); - - if ui.is_rect_visible(response.rect) { - let text_pos = ui - .layout() - .align_size_within_rect(text.size(), rect.shrink2(button_padding)) - .min; - - let visuals = ui.style().interact_selectable(&response, selected); - - if selected - || response.highlighted() - || response.has_focus() - || (response.hovered() && !whitelisted) - { - let rect = rect.expand(visuals.expansion); - - ui.painter().rect( - rect, - visuals.corner_radius, - visuals.weak_bg_fill, - visuals.bg_stroke, - StrokeKind::Middle, - ); - } else if response.hovered() && whitelisted { - let rect = rect.expand(visuals.expansion); - ui.painter().rect( - rect, - visuals.corner_radius, - Color32::from_rgb(255, 127, 80), - visuals.bg_stroke, - StrokeKind::Middle, - ); - } else if whitelisted { - let rect = rect.expand(visuals.expansion); - let is_dark_theme = ui.visuals().dark_mode; - - let color = if is_dark_theme { - Color32::from_rgb(168, 100, 66) - } else { - Color32::from_rgb(255, 160, 122) - }; - - ui.painter().rect( - rect, - visuals.corner_radius, - color, - visuals.bg_stroke, - StrokeKind::Middle, - ); - } - - ui.painter().galley(text_pos, text, visuals.text_color()); - } - - response - } -} diff --git a/src/utils.rs b/src/utils.rs deleted file mode 100644 index adcd444..0000000 --- a/src/utils.rs +++ /dev/null @@ -1,461 +0,0 @@ -use chrono::{Local, NaiveDate, NaiveDateTime}; -use egui_selectable_table::SelectableRow; -use log::{error, info}; -use serde::{Deserialize, Serialize}; -use std::collections::{BTreeMap, HashMap, HashSet}; -use std::error::Error; -use std::fmt::Write as _; -use std::fs::{self, File}; -use std::io::{Read, Write}; -use std::path::PathBuf; -use tokio::runtime::{self, Runtime}; - -use crate::ui_components::TGKeys; -use crate::ui_components::processor::{ - ChartTiming, ColumnName, PackedBlacklistedUser, PackedWhitelistedUser, ParsedChat, -}; -use crate::ui_components::tab_ui::UserRowData; - -#[derive(Serialize, Deserialize)] -pub struct IsLightTheme { - is_light: bool, -} - -/// Finds all the saved session files -pub fn find_session_files() -> Vec { - let mut sessions = Vec::new(); - if let Ok(entries) = fs::read_dir(".") { - for entry in entries { - if let Ok(file_name) = entry.unwrap().file_name().into_string() - && file_name.ends_with(".session") - { - info!("Found existing session file {file_name}"); - sessions.push(file_name); - } - } - } - sessions -} - -/// Convert inserted chat points into textual representation -pub fn chat_to_text(start: &str, end: &str) -> String { - let chat_data: BTreeMap = - parse_chat_details(start, end).into_iter().collect(); - - let mut text_data = "Detected Chats:".to_string(); - - for (name, parsed) in chat_data { - let mut chat_text = format!(" {name}"); - - if let Some(end_point) = parsed.end_point() { - let _ = write!(chat_text, ": {end_point} - "); - - if let Some(start_point) = parsed.start_point() { - let _ = write!(chat_text, "{start_point}"); - } else { - chat_text += "∞"; - } - } else if let Some(start_point) = parsed.start_point() { - chat_text += ": 1 - "; - let _ = write!(chat_text, "{start_point}"); - } else { - chat_text += ": ∞"; - } - let _ = write!(text_data, " {chat_text}"); - } - - text_data -} - -/// Parse start and end point strings as parsed chat points -pub fn parse_chat_details(start: &str, end: &str) -> HashMap { - let start_chat_list: Vec<&str> = start.split_whitespace().collect(); - let end_chat_list: Vec<&str> = end.split_whitespace().collect(); - - let mut parsed_chat_list = HashMap::new(); - - for chat in start_chat_list { - let (name, num) = parse_tg_chat(chat); - if name.is_none() { - error!("{chat} is getting ignored as no chat name was found"); - continue; - } - - let name = name.unwrap(); - let parsed = ParsedChat::new(name.clone(), num, None); - parsed_chat_list.insert(name, parsed); - } - - for chat in end_chat_list { - let (name, num) = parse_tg_chat(chat); - if name.is_none() { - error!("{chat} is getting ignored as no chat name was found"); - continue; - } - - let name = name.unwrap(); - if let Some(parsed) = parsed_chat_list.get_mut(&name) { - if let Some(end_num) = num { - let completed = parsed.set_end_point(end_num); - if !completed { - error!( - "End point cannot be equal or bigger than start point. Ignoring the end point for {chat}" - ); - } - } - } else { - error!("{chat} was not found in the start point, this will be ignored"); - } - } - - parsed_chat_list -} - -/// Tries to parse a link to get the chat name and the message ID -pub fn parse_tg_chat(text: &str) -> (Option, Option) { - if text.is_empty() { - return (None, None); - } - - let mut chat_name = None; - let mut message_number = None; - - // Example t.me/chat_name/1234 - if text.contains("t.me") { - // split expected result t.me and chat_name/1234 - let split_text = text.split_once("t.me/"); - if let Some((_first, second)) = split_text { - // It will be either chat_name/number or chat_name - // if chat_name/number split it again and get the number - // otherwise set whatever value is remaining as the parsed chat name - if second.contains('/') { - (chat_name, message_number) = split_tg_link(second); - } else { - chat_name = Some(second.to_string()); - } - } - } else if text.starts_with('@') { - // Example @chat_name/1234 - let split_text = text.split_once('@'); - // // split expected result @ and chat_name/1234 - if let Some((_first, second)) = split_text { - if second.contains('/') { - (chat_name, message_number) = split_tg_link(second); - } else if !second.is_empty() { - chat_name = Some(second.to_string()); - } - } - } else { - // Example chat_name. If invalid, it will still be caught here, later will get verified by the telegram side - if text.contains('/') { - (chat_name, message_number) = split_tg_link(text); - } else { - chat_name = Some(text.to_string()); - } - } - (chat_name, message_number) -} - -/// Splits a string on slash and tries to get the tg chat name and message number -fn split_tg_link(text: &str) -> (Option, Option) { - let mut chat_name = None; - let mut message_number = None; - - if let Some((name, num)) = text.split_once('/') { - chat_name = Some(name.to_string()); - if let Ok(num) = num.parse() { - message_number = Some(num); - } - } - - (chat_name, message_number) -} - -/// Returns the proper emoji based on light or dark value -pub fn theme_hover_text(is_light_theme: bool) -> String { - if is_light_theme { - "Switch to dark theme".to_string() - } else { - "Switch to light theme".to_string() - } -} - -/// Convenient tokio runtime getter -pub fn get_runtime() -> Runtime { - runtime::Builder::new_multi_thread() - .worker_threads(99) - .enable_all() - .build() - .unwrap() -} - -/// Tries to read the API key json file -pub fn get_api_keys() -> Option { - let mut to_return = None; - let mut api_key_path = PathBuf::from("."); - api_key_path.push("api_keys.json"); - - let file = File::open(api_key_path); - - if let Ok(mut file) = file { - let mut contents = String::new(); - file.read_to_string(&mut contents) - .expect("Failed to read file"); - - let result = serde_json::from_str::(&contents); - if let Ok(result) = result - && !result.api_id.is_empty() - && !result.api_hash.is_empty() - { - to_return = Some(result); - } - } - - to_return -} - -/// Saves the API keys in a json file -pub fn save_api_keys(api_keys: &TGKeys) { - let data = serde_json::to_string(api_keys); - - if let Ok(data) = data { - let mut api_key_path = PathBuf::from("."); - api_key_path.push("api_keys.json"); - let mut file = File::create(api_key_path).unwrap(); - file.write_all(data.as_bytes()).unwrap(); - } -} - -/// Reads the whitelisted user `PackedChat` Hex IDs and returns them -pub fn get_whitelisted() -> Result, Box> { - let mut whitelist_path = PathBuf::from("."); - whitelist_path.push("whitelist.json"); - - let file = File::open(whitelist_path); - - if let Ok(mut file) = file { - let mut contents = String::new(); - file.read_to_string(&mut contents)?; - let users = serde_json::from_str(&contents)?; - Ok(users) - } else { - Ok(Vec::new()) - } -} - -/// Reads the blacklisted user `PackedChat` Hex IDs and returns them -pub fn get_blacklisted() -> Result, Box> { - let mut blacklist_path = PathBuf::from("."); - blacklist_path.push("blacklist.json"); - - let file = File::open(blacklist_path); - - if let Ok(mut file) = file { - let mut contents = String::new(); - file.read_to_string(&mut contents)?; - let users = serde_json::from_str(&contents)?; - Ok(users) - } else { - Ok(Vec::new()) - } -} -/// Saves `PackedChat` Hex strings to a json file -pub fn save_whitelisted_users(packed_chats: Vec, overwrite: bool) { - // HashSet to avoid duplicate whitelisted users - let mut existing_data = HashSet::new(); - - let mut whitelist_path = PathBuf::from("."); - whitelist_path.push("whitelist.json"); - - let file = File::open(&whitelist_path); - - if !overwrite && let Ok(mut file) = file { - let mut contents = String::new(); - file.read_to_string(&mut contents) - .expect("Failed to read file"); - - existing_data = serde_json::from_str(&contents).unwrap(); - } - - existing_data.extend(packed_chats); - - let data = serde_json::to_string(&existing_data).unwrap(); - - let mut file = File::create(whitelist_path).unwrap(); - file.write_all(data.as_bytes()).unwrap(); -} - -/// Saves `PackedChat` Hex strings to a json file -pub fn save_blacklisted_users(packed_chats: Vec, overwrite: bool) { - // HashSet to avoid duplicate whitelisted users - let mut existing_data = HashSet::new(); - - let mut whitelist_path = PathBuf::from("."); - whitelist_path.push("blacklist.json"); - - let file = File::open(&whitelist_path); - - if !overwrite && let Ok(mut file) = file { - let mut contents = String::new(); - file.read_to_string(&mut contents) - .expect("Failed to read file"); - - existing_data = serde_json::from_str(&contents).unwrap(); - } - - existing_data.extend(packed_chats); - - let data = serde_json::to_string(&existing_data).unwrap(); - - let mut file = File::create(whitelist_path).unwrap(); - file.write_all(data.as_bytes()).unwrap(); -} - -/// Tries to find and read the Font files -pub fn get_font_data() -> Option<(Vec, Vec)> { - let mut gentium_font = PathBuf::from("."); - let mut cjk_font = PathBuf::from("."); - - gentium_font.push("fonts"); - cjk_font.push("fonts"); - fs::create_dir_all(&gentium_font).unwrap(); - - gentium_font.push("GentiumBookPlus-Regular.ttf"); - cjk_font.push("NotoSansCJK-Regular.ttc"); - - let mut gentium_font_data = Vec::new(); - let mut cjk_font_data = Vec::new(); - - if let Ok(mut file) = File::open(gentium_font) { - file.read_to_end(&mut gentium_font_data) - .expect("Failed to read file"); - } else { - return None; - } - - if let Ok(mut file) = File::open(cjk_font) { - file.read_to_end(&mut cjk_font_data) - .expect("Failed to read file"); - } else { - return None; - } - - Some((cjk_font_data, gentium_font_data)) -} - -/// Convenient function to format `NaiveDateTime` to string. Used for the Chart UI -pub fn time_to_string(time: &NaiveDateTime, timing: ChartTiming) -> String { - match timing { - ChartTiming::Hourly => time.to_string(), - _ => time.format("%Y-%m-%d").to_string(), - } -} - -/// Convenient function to convert u8 to a Week name string. used for the Chart UI -pub fn weekday_num_to_string(weekday: u8) -> String { - match weekday { - 0 => String::from("Monday"), - 1 => String::from("Tuesday"), - 2 => String::from("Wednesday"), - 3 => String::from("Thursday"), - 4 => String::from("Friday"), - 5 => String::from("Saturday"), - 6 => String::from("Sunday"), - _ => unreachable!(), - } -} - -pub fn export_table_data(rows: &Vec>, name: &str) { - let mut export_file_location = PathBuf::from("."); - let current_time = Local::now(); - let formatted_time = current_time.format("%Y-%m-%d %H-%M-%S").to_string(); - let file_name = format!("{name} Table Export {formatted_time}.csv"); - - export_file_location.push(file_name); - let file = File::create(export_file_location).unwrap(); - - let mut wtr = csv::Writer::from_writer(file); - - for row in rows { - let row = &row.row_data; - if let Err(e) = wtr.serialize(row) { - error!("Failed to add one row, skipping. Error: {e}"); - } - } - - wtr.flush().unwrap(); -} - -pub fn separate_whitelist_by_seen( - whitelist_data: Vec, -) -> HashMap> { - let mut separated_data = HashMap::new(); - - for data in whitelist_data { - let entry = separated_data.entry(data.seen_by).or_insert(Vec::new()); - entry.push(data.hex_value); - } - - separated_data -} - -pub fn separate_blacklist_by_seen( - whitelist_data: Vec, -) -> HashMap> { - let mut separated_data = HashMap::new(); - - for data in whitelist_data { - let entry = separated_data.entry(data.seen_by).or_insert(Vec::new()); - entry.push(data.hex_value); - } - - separated_data -} -/// Checks for a value in the `HashMap` of a `HashMap` -pub fn entry_insert_user( - user_data: &mut HashMap>, - user_row_data: UserRowData, - id: i64, - date: NaiveDate, -) { - let entry = user_data.entry(date).or_default(); - entry.entry(id).or_insert(user_row_data.clone()); -} - -pub fn to_chart_name(user_name: String, full_name: &str, user_id: i64) -> String { - if user_name != "Empty" { - user_name - } else if full_name == "Deleted Account" { - user_id.to_string() - } else { - format!("{full_name} {user_id}") - } -} - -pub fn last_theme() -> Result> { - let mut theme_json = PathBuf::from("."); - theme_json.push("theme.json"); - - if let Ok(mut file) = File::open(theme_json) { - let mut contents = String::new(); - file.read_to_string(&mut contents)?; - - let existing_data: IsLightTheme = serde_json::from_str(&contents)?; - Ok(existing_data.is_light) - } else { - Ok(true) - } -} - -pub fn save_theme(status: bool) { - let new_data = IsLightTheme { is_light: status }; - - let data = serde_json::to_string(&new_data); - - if let Ok(data) = data { - let mut theme_path = PathBuf::from("."); - theme_path.push("theme.json"); - let mut file = File::create(theme_path).unwrap(); - file.write_all(data.as_bytes()).unwrap(); - } -} diff --git a/src/utils/chat_link.rs b/src/utils/chat_link.rs new file mode 100644 index 0000000..49531eb --- /dev/null +++ b/src/utils/chat_link.rs @@ -0,0 +1,139 @@ +use log::error; +use std::collections::{BTreeMap, HashMap}; +use std::fmt::Write as _; + +use crate::ui::state::ParsedChat; + +/// Convert inserted chat points into textual representation +pub fn chat_to_text(start: &str, end: &str) -> String { + let chat_data: BTreeMap = + parse_chat_details(start, end).into_iter().collect(); + + let mut text_data = "Detected Chats:".to_string(); + + for (name, parsed) in chat_data { + let mut chat_text = format!(" {name}"); + + if let Some(end_point) = parsed.end_point() { + let _ = write!(chat_text, ": {end_point} - "); + + if let Some(start_point) = parsed.start_point() { + let _ = write!(chat_text, "{start_point}"); + } else { + chat_text += "∞"; + } + } else if let Some(start_point) = parsed.start_point() { + chat_text += ": 1 - "; + let _ = write!(chat_text, "{start_point}"); + } else { + chat_text += ": ∞"; + } + let _ = write!(text_data, " {chat_text}"); + } + + text_data +} + +/// Parse start and end point strings as parsed chat points +pub fn parse_chat_details(start: &str, end: &str) -> HashMap { + let start_chat_list: Vec<&str> = start.split_whitespace().collect(); + let end_chat_list: Vec<&str> = end.split_whitespace().collect(); + + let mut parsed_chat_list = HashMap::new(); + + for chat in start_chat_list { + let (name, num) = parse_tg_chat(chat); + if name.is_none() { + error!("{chat} is getting ignored as no chat name was found"); + continue; + } + + let name = name.unwrap(); + let parsed = ParsedChat::new(name.clone(), num, None); + parsed_chat_list.insert(name, parsed); + } + + for chat in end_chat_list { + let (name, num) = parse_tg_chat(chat); + if name.is_none() { + error!("{chat} is getting ignored as no chat name was found"); + continue; + } + + let name = name.unwrap(); + if let Some(parsed) = parsed_chat_list.get_mut(&name) { + if let Some(end_num) = num { + let completed = parsed.set_end_point(end_num); + if !completed { + error!( + "End point cannot be equal or bigger than start point. Ignoring the end point for {chat}" + ); + } + } + } else { + error!("{chat} was not found in the start point, this will be ignored"); + } + } + + parsed_chat_list +} + +/// Tries to parse a link to get the chat name and the message ID +pub fn parse_tg_chat(text: &str) -> (Option, Option) { + if text.is_empty() { + return (None, None); + } + + let mut chat_name = None; + let mut message_number = None; + + // Example t.me/chat_name/1234 + if text.contains("t.me") { + // split expected result t.me and chat_name/1234 + let split_text = text.split_once("t.me/"); + if let Some((_first, second)) = split_text { + // It will be either chat_name/number or chat_name + // if chat_name/number split it again and get the number + // otherwise set whatever value is remaining as the parsed chat name + if second.contains('/') { + (chat_name, message_number) = split_tg_link(second); + } else { + chat_name = Some(second.to_string()); + } + } + } else if text.starts_with('@') { + // Example @chat_name/1234 + let split_text = text.split_once('@'); + // // split expected result @ and chat_name/1234 + if let Some((_first, second)) = split_text { + if second.contains('/') { + (chat_name, message_number) = split_tg_link(second); + } else if !second.is_empty() { + chat_name = Some(second.to_string()); + } + } + } else { + // Example chat_name. If invalid, it will still be caught here, later will get verified by the telegram side + if text.contains('/') { + (chat_name, message_number) = split_tg_link(text); + } else { + chat_name = Some(text.to_string()); + } + } + (chat_name, message_number) +} + +/// Splits a string on slash and tries to get the tg chat name and message number +fn split_tg_link(text: &str) -> (Option, Option) { + let mut chat_name = None; + let mut message_number = None; + + if let Some((name, num)) = text.split_once('/') { + chat_name = Some(name.to_string()); + if let Ok(num) = num.parse() { + message_number = Some(num); + } + } + + (chat_name, message_number) +} diff --git a/src/utils/format.rs b/src/utils/format.rs new file mode 100644 index 0000000..ba61aef --- /dev/null +++ b/src/utils/format.rs @@ -0,0 +1,87 @@ +use egui_selectable_table::SelectableRow; +use jiff::Zoned; +use jiff::civil::{Date, DateTime}; +use log::error; +use std::collections::HashMap; +use std::fs::File; +use std::path::PathBuf; + +use crate::ui::state::{ChartTiming, ColumnName}; +use crate::ui::tabs::UserRowData; + +/// Returns the proper text based on light or dark value +pub fn theme_hover_text(is_light_theme: bool) -> String { + if is_light_theme { + "Switch to dark theme".to_string() + } else { + "Switch to light theme".to_string() + } +} + +/// Formats a date and time as `2025-01-31 14:05:09`. Used by the table and the charts +pub fn format_datetime(time: &DateTime) -> String { + time.strftime("%Y-%m-%d %H:%M:%S").to_string() +} + +/// Convenient function to format a `DateTime` to string. Used for the Chart UI +pub fn time_to_string(time: &DateTime, timing: ChartTiming) -> String { + match timing { + ChartTiming::Hourly => format_datetime(time), + _ => time.date().to_string(), + } +} + +/// Convenient function to convert u8 to a Week name string. used for the Chart UI +pub fn weekday_num_to_string(weekday: u8) -> String { + match weekday { + 0 => String::from("Monday"), + 1 => String::from("Tuesday"), + 2 => String::from("Wednesday"), + 3 => String::from("Thursday"), + 4 => String::from("Friday"), + 5 => String::from("Saturday"), + 6 => String::from("Sunday"), + _ => unreachable!(), + } +} + +pub fn export_table_data(rows: &Vec>, name: &str) { + let mut export_file_location = PathBuf::from("."); + let formatted_time = Zoned::now().strftime("%Y-%m-%d %H-%M-%S").to_string(); + let file_name = format!("{name} Table Export {formatted_time}.csv"); + + export_file_location.push(file_name); + let file = File::create(export_file_location).unwrap(); + + let mut wtr = csv::Writer::from_writer(file); + + for row in rows { + let row = &row.row_data; + if let Err(e) = wtr.serialize(row) { + error!("Failed to add one row, skipping. Error: {e}"); + } + } + + wtr.flush().unwrap(); +} + +/// Checks for a value in the `HashMap` of a `HashMap` +pub fn entry_insert_user( + user_data: &mut HashMap>, + user_row_data: UserRowData, + id: i64, + date: Date, +) { + let entry = user_data.entry(date).or_default(); + entry.entry(id).or_insert(user_row_data.clone()); +} + +pub fn to_chart_name(user_name: String, full_name: &str, user_id: i64) -> String { + if user_name != "Empty" { + user_name + } else if full_name == "Deleted Account" { + user_id.to_string() + } else { + format!("{full_name} {user_id}") + } +} diff --git a/src/utils/mod.rs b/src/utils/mod.rs new file mode 100644 index 0000000..4331e0d --- /dev/null +++ b/src/utils/mod.rs @@ -0,0 +1,9 @@ +mod chat_link; +mod format; +mod runtime; +mod storage; + +pub use chat_link::*; +pub use format::*; +pub use runtime::*; +pub use storage::*; diff --git a/src/utils/runtime.rs b/src/utils/runtime.rs new file mode 100644 index 0000000..07723e5 --- /dev/null +++ b/src/utils/runtime.rs @@ -0,0 +1,9 @@ +use tokio::runtime::{self, Runtime}; + +/// Convenient tokio runtime getter +pub fn get_runtime() -> Runtime { + runtime::Builder::new_multi_thread() + .enable_all() + .build() + .unwrap() +} diff --git a/src/utils/storage.rs b/src/utils/storage.rs new file mode 100644 index 0000000..56f83b7 --- /dev/null +++ b/src/utils/storage.rs @@ -0,0 +1,154 @@ +use grammers_session::types::PeerRef; +use log::{error, info}; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::error::Error; +use std::fs::{self, File}; +use std::io::{Read, Write}; +use std::path::PathBuf; + +use crate::ui::TGKeys; +use crate::ui::state::{ListKind, PackedUser}; + +#[derive(Serialize, Deserialize)] +pub struct IsLightTheme { + is_light: bool, +} + +/// Finds all the saved session files +pub fn find_session_files() -> Vec { + let mut sessions = Vec::new(); + if let Ok(entries) = fs::read_dir(".") { + for entry in entries { + if let Ok(file_name) = entry.unwrap().file_name().into_string() + && file_name.ends_with(".sqlite") + { + info!("Found existing session file {file_name}"); + sessions.push(file_name); + } + } + } + sessions +} + +/// Tries to read the API key json file +pub fn get_api_keys() -> Option { + let mut to_return = None; + let mut api_key_path = PathBuf::from("."); + api_key_path.push("api_keys.json"); + + let file = File::open(api_key_path); + + if let Ok(mut file) = file { + let mut contents = String::new(); + file.read_to_string(&mut contents) + .expect("Failed to read file"); + + let result = serde_json::from_str::(&contents); + if let Ok(result) = result + && !result.api_id.is_empty() + && !result.api_hash.is_empty() + { + to_return = Some(result); + } + } + + to_return +} + +/// Saves the API keys in a json file +pub fn save_api_keys(api_keys: &TGKeys) { + let data = serde_json::to_string(api_keys); + + if let Ok(data) = data { + let mut api_key_path = PathBuf::from("."); + api_key_path.push("api_keys.json"); + let mut file = File::create(api_key_path).unwrap(); + file.write_all(data.as_bytes()).unwrap(); + } +} + +/// Reads the saved user `PeerRef` values of a list and returns them +pub fn get_saved_users(kind: ListKind) -> Result, Box> { + let path = PathBuf::from(".").join(kind.file_name()); + + if let Ok(mut file) = File::open(path) { + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + let users = serde_json::from_str(&contents)?; + Ok(users) + } else { + Ok(Vec::new()) + } +} + +/// Saves `PeerRef` values of a list to its json file +pub fn save_users(kind: ListKind, packed_chats: Vec, overwrite: bool) { + // HashSet to avoid duplicate users + let mut existing_data = HashSet::new(); + + let path = PathBuf::from(".").join(kind.file_name()); + + if !overwrite && let Ok(mut file) = File::open(&path) { + let mut contents = String::new(); + file.read_to_string(&mut contents) + .expect("Failed to read file"); + + existing_data = serde_json::from_str(&contents).unwrap(); + } + + existing_data.extend(packed_chats); + + let data = serde_json::to_string(&existing_data).unwrap(); + + let mut file = File::create(path).unwrap(); + file.write_all(data.as_bytes()).unwrap(); +} + +/// Groups the saved users by the session that saw them +pub fn separate_by_seen(kind: ListKind, saved: Vec) -> HashMap> { + let mut separated_data = HashMap::new(); + + for data in saved { + let Some(peer_ref) = data.peer_ref() else { + error!( + "Invalid peer id {} found in {}, skipping", + data.peer_id, + kind.name() + ); + continue; + }; + let entry = separated_data.entry(data.seen_by).or_insert(Vec::new()); + entry.push(peer_ref); + } + + separated_data +} + +pub fn last_theme() -> Result> { + let mut theme_json = PathBuf::from("."); + theme_json.push("theme.json"); + + if let Ok(mut file) = File::open(theme_json) { + let mut contents = String::new(); + file.read_to_string(&mut contents)?; + + let existing_data: IsLightTheme = serde_json::from_str(&contents)?; + Ok(existing_data.is_light) + } else { + Ok(true) + } +} + +pub fn save_theme(status: bool) { + let new_data = IsLightTheme { is_light: status }; + + let data = serde_json::to_string(&new_data); + + if let Ok(data) = data { + let mut theme_path = PathBuf::from("."); + theme_path.push("theme.json"); + let mut file = File::create(theme_path).unwrap(); + file.write_all(data.as_bytes()).unwrap(); + } +} diff --git a/tombi.toml b/tombi.toml new file mode 100644 index 0000000..7499a40 --- /dev/null +++ b/tombi.toml @@ -0,0 +1,6 @@ +toml-version = "v1.0.0" + +[[schemas]] +toml-version = "v1.0.0" +path = "tombi://www.schemastore.org/cargo.json" +include = ["Cargo.toml"]