Skip to content

Instantly share code, notes, and snippets.

@Plecra
Created November 16, 2020 14:24
Show Gist options
  • Save Plecra/42616910c382cc9395e68228f5df3a76 to your computer and use it in GitHub Desktop.
Save Plecra/42616910c382cc9395e68228f5df3a76 to your computer and use it in GitHub Desktop.
Logging demo
[package]
name = "keylogger"
version = "0.1.0"
authors = ["..."]
edition = "2018"
[dependencies]
winit = { version = "0.23.0", features = ["serde"] }
chrono = { version = "0.4.19", features = ["serde"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0.59"
ctrlc = "3.1.7"
use chrono::{DateTime, Utc};
use keylogger::Input;
use serde_json::de::Deserializer;
use std::collections::HashMap;
use std::{fs, io};
fn main() -> io::Result<()> {
let mut map = HashMap::new();
for (input, time) in Deserializer::from_reader(fs::File::open("./data/data.log")?)
.into_iter::<(Input, DateTime<Utc>)>()
.filter_map(|r| r.ok())
{
*map.entry(input).or_insert(0) += 1;
}
for (input, count) in &map {
println!("{:?}: {}", input, count);
}
Ok(())
}
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum Input {
Key(winit::event::VirtualKeyCode),
RightClick,
LeftClick,
MiddleClick,
}
use chrono::Utc;
use keylogger::Input;
use std::{fs, io};
use winit::{
event::{DeviceEvent, ElementState, Event, KeyboardInput, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
fn main() -> io::Result<()> {
fs::create_dir_all("./data")?;
let mut logfile = io::BufWriter::new(
fs::OpenOptions::new()
.create(true)
.append(true)
.open("./data/data.log")?,
);
let event_loop = EventLoop::<()>::with_user_event();
let proxy = event_loop.create_proxy();
ctrlc::set_handler(move || proxy.send_event(()).expect("ctrl c received late"))
.expect("couldn't set exit hook");
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;
let input = match event {
// Fired on each Button click event
Event::DeviceEvent {
event:
DeviceEvent::Button {
button,
state: ElementState::Released,
},
..
} => match button {
1 => Input::LeftClick,
2 => Input::MiddleClick,
3 => Input::RightClick,
_ => return,
},
// Fired on each key event
Event::DeviceEvent {
event:
DeviceEvent::Key(KeyboardInput {
virtual_keycode: Some(key),
state: ElementState::Released,
..
}),
..
} => Input::Key(key),
// Won't work if no windows
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
}
| Event::UserEvent(()) => return *control_flow = ControlFlow::Exit,
_ => return,
};
if let Err(e) = serde_json::to_writer(&mut logfile, &(input, Utc::now())) {
eprintln!("lost log: {}", e);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment