feat: integrate event tracking for hotkey actions, history management, and settings updates

This commit is contained in:
PandaDEV 2024-12-23 14:34:21 +10:00
parent 3824f24be4
commit f44be512fe
No known key found for this signature in database
GPG key ID: 13EFF9BAF70EE75C
8 changed files with 149 additions and 36 deletions

View file

@ -1,3 +1,4 @@
use tauri_plugin_aptabase::EventTracker;
use base64::{engine::general_purpose::STANDARD, Engine};
// use hyperpolyglot;
use lazy_static::lazy_static;
@ -7,7 +8,7 @@ use sqlx::SqlitePool;
use std::fs;
use std::sync::atomic::{AtomicBool, Ordering};
use std::{thread, time::Duration};
use tauri::{AppHandle, Emitter, Listener, Manager, Runtime};
use tauri::{AppHandle, Emitter, Listener, Manager};
use tauri_plugin_clipboard::Clipboard;
use tokio::runtime::Runtime as TokioRuntime;
use url::Url;
@ -23,8 +24,8 @@ lazy_static! {
}
#[tauri::command]
pub async fn write_and_paste<R: Runtime>(
app_handle: tauri::AppHandle<R>,
pub async fn write_and_paste(
app_handle: AppHandle,
content: String,
content_type: String,
) -> Result<(), String> {
@ -80,39 +81,44 @@ pub async fn write_and_paste<R: Runtime>(
IS_PROGRAMMATIC_PASTE.store(false, Ordering::SeqCst);
});
let _ = app_handle.track_event("clipboard_paste", Some(serde_json::json!({
"content_type": content_type
})));
Ok(())
}
pub fn setup<R: Runtime>(app: &AppHandle<R>) {
let app = app.clone();
pub fn setup(app: &AppHandle) {
let app_handle = app.clone();
let runtime = TokioRuntime::new().expect("Failed to create Tokio runtime");
app.clone().listen(
app_handle.clone().listen(
"plugin:clipboard://clipboard-monitor/update",
move |_event| {
let app = app.clone();
let app_handle = app_handle.clone();
runtime.block_on(async move {
if IS_PROGRAMMATIC_PASTE.load(Ordering::SeqCst) {
return;
}
let clipboard = app.state::<Clipboard>();
let clipboard = app_handle.state::<Clipboard>();
let available_types = clipboard.available_types().unwrap();
let (app_name, app_icon) = get_app_info();
match get_pool(&app).await {
match get_pool(&app_handle).await {
Ok(pool) => {
if available_types.image {
println!("Handling image change");
if let Ok(image_data) = clipboard.read_image_base64() {
let file_path = save_image_to_file(&app, &image_data)
let file_path = save_image_to_file(&app_handle, &image_data)
.await
.map_err(|e| e.to_string())
.unwrap_or_else(|e| e);
let _ = db::history::add_history_item(
app_handle.clone(),
pool,
HistoryItem::new(app_name, ContentType::Image, file_path, None, app_icon, None),
HistoryItem::new(app_name, ContentType::Image, file_path, None, app_icon, None)
).await;
}
} else if available_types.files {
@ -120,6 +126,7 @@ pub fn setup<R: Runtime>(app: &AppHandle<R>) {
if let Ok(files) = clipboard.read_files() {
for file in files {
let _ = db::history::add_history_item(
app_handle.clone(),
pool.clone(),
HistoryItem::new(
app_name.clone(),
@ -135,6 +142,7 @@ pub fn setup<R: Runtime>(app: &AppHandle<R>) {
} else if available_types.text {
println!("Handling text change");
if let Ok(text) = clipboard.read_text() {
let text = text.to_string();
let url_regex = Regex::new(r"^https?://(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&//=]*)$").unwrap();
if url_regex.is_match(&text) {
@ -145,6 +153,7 @@ pub fn setup<R: Runtime>(app: &AppHandle<R>) {
};
let _ = db::history::add_history_item(
app_handle.clone(),
pool,
HistoryItem::new(app_name, ContentType::Link, text, favicon, app_icon, None)
).await;
@ -167,13 +176,15 @@ pub fn setup<R: Runtime>(app: &AppHandle<R>) {
).await;
} else*/ if crate::utils::commands::detect_color(&text) {
let _ = db::history::add_history_item(
app_handle.clone(),
pool,
HistoryItem::new(app_name, ContentType::Color, text, None, app_icon, None)
).await;
} else {
let _ = db::history::add_history_item(
app_handle.clone(),
pool,
HistoryItem::new(app_name, ContentType::Text, text, None, app_icon, None)
HistoryItem::new(app_name, ContentType::Text, text.clone(), None, app_icon, None)
).await;
}
}
@ -187,14 +198,20 @@ pub fn setup<R: Runtime>(app: &AppHandle<R>) {
}
}
let _ = app.emit("clipboard-content-updated", ());
let _ = app_handle.emit("clipboard-content-updated", ());
let _ = app_handle.track_event("clipboard_copied", Some(serde_json::json!({
"content_type": if available_types.image { "image" }
else if available_types.files { "files" }
else if available_types.text { "text" }
else { "unknown" }
})));
});
},
);
}
async fn get_pool<R: Runtime>(
app_handle: &AppHandle<R>,
async fn get_pool(
app_handle: &AppHandle,
) -> Result<tauri::State<'_, SqlitePool>, Box<dyn std::error::Error + Send + Sync>> {
Ok(app_handle.state::<SqlitePool>())
}
@ -211,8 +228,8 @@ pub fn start_monitor(app_handle: AppHandle) -> Result<(), String> {
Ok(())
}
async fn save_image_to_file<R: Runtime>(
app_handle: &AppHandle<R>,
async fn save_image_to_file(
app_handle: &AppHandle,
base64_data: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let app_data_dir = app_handle.path().app_data_dir().unwrap();

View file

@ -1,3 +1,4 @@
use tauri_plugin_aptabase::EventTracker;
use crate::utils::commands::center_window_on_current_monitor;
use global_hotkey::{
hotkey::{Code, HotKey, Modifiers},
@ -142,4 +143,8 @@ fn handle_hotkey_event(app_handle: &AppHandle) {
center_window_on_current_monitor(&window);
}
let _ = app_handle.track_event("hotkey_triggered", Some(serde_json::json!({
"action": if window.is_visible().unwrap() { "hide" } else { "show" }
})));
}

View file

@ -3,10 +3,14 @@ use tauri::{
tray::TrayIconBuilder,
Emitter, Manager,
};
use tauri_plugin_aptabase::EventTracker;
pub fn setup(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
let window = app.get_webview_window("main").unwrap();
let window_clone_for_tray = window.clone();
let is_visible = window.is_visible().unwrap();
let _ = app.track_event("tray_toggle", Some(serde_json::json!({
"action": if is_visible { "hide" } else { "show" }
})));
let icon_bytes = include_bytes!("../../icons/Square71x71Logo.png");
let icon = tauri::image::Image::from_bytes(icon_bytes).unwrap();
@ -24,20 +28,25 @@ pub fn setup(app: &mut tauri::App) -> Result<(), Box<dyn std::error::Error>> {
)
.on_menu_event(move |_app, event| match event.id().as_ref() {
"quit" => {
let _ = _app.track_event("app_quit", None);
std::process::exit(0);
}
"show" => {
let is_visible = window_clone_for_tray.is_visible().unwrap();
let _ = _app.track_event("tray_toggle", Some(serde_json::json!({
"action": if is_visible { "hide" } else { "show" }
})));
let is_visible = window.is_visible().unwrap();
if is_visible {
window_clone_for_tray.hide().unwrap();
window.hide().unwrap();
} else {
window_clone_for_tray.show().unwrap();
window_clone_for_tray.set_focus().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
window_clone_for_tray.emit("main_route", ()).unwrap();
window.emit("main_route", ()).unwrap();
}
"keybind" => {
window_clone_for_tray.emit("change_keybind", ()).unwrap();
let _ = _app.track_event("tray_keybind_change", None);
window.emit("change_keybind", ()).unwrap();
}
_ => (),
})

View file

@ -4,6 +4,7 @@ use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use sqlx::{Row, SqlitePool};
use std::fs;
use tauri_plugin_aptabase::EventTracker;
pub async fn initialize_history(pool: &SqlitePool) -> Result<(), Box<dyn std::error::Error>> {
let id: String = thread_rng()
@ -53,6 +54,7 @@ pub async fn get_history(pool: tauri::State<'_, SqlitePool>) -> Result<Vec<Histo
#[tauri::command]
pub async fn add_history_item(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>,
item: HistoryItem,
) -> Result<(), String> {
@ -95,6 +97,10 @@ pub async fn add_history_item(
}
}
let _ = app_handle.track_event("history_item_added", Some(serde_json::json!({
"content_type": item.content_type.to_string()
})));
Ok(())
}
@ -163,6 +169,7 @@ pub async fn load_history_chunk(
#[tauri::command]
pub async fn delete_history_item(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>,
id: String,
) -> Result<(), String> {
@ -172,16 +179,23 @@ pub async fn delete_history_item(
.await
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("history_item_deleted", None);
Ok(())
}
#[tauri::command]
pub async fn clear_history(pool: tauri::State<'_, SqlitePool>) -> Result<(), String> {
pub async fn clear_history(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>
) -> Result<(), String> {
sqlx::query("DELETE FROM history")
.execute(&*pool)
.await
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("history_cleared", None);
Ok(())
}

View file

@ -3,6 +3,7 @@ use serde_json;
use sqlx::Row;
use sqlx::SqlitePool;
use tauri::{Emitter, Manager};
use tauri_plugin_aptabase::EventTracker;
#[derive(Deserialize, Serialize)]
struct KeybindSetting {
@ -26,9 +27,16 @@ pub async fn initialize_settings(pool: &SqlitePool) -> Result<(), Box<dyn std::e
#[tauri::command]
pub async fn save_keybind(
app_handle: tauri::AppHandle,
keybind: Vec<String>,
pool: tauri::State<'_, SqlitePool>,
keybind: Vec<String>,
) -> Result<(), String> {
let keybind_str = keybind.join("+");
let keybind_clone = keybind_str.clone();
app_handle
.emit("update-shortcut", &keybind_str)
.map_err(|e| e.to_string())?;
let json = serde_json::to_string(&keybind).map_err(|e| e.to_string())?;
sqlx::query("INSERT OR REPLACE INTO settings (key, value) VALUES ('keybind', ?)")
@ -37,10 +45,9 @@ pub async fn save_keybind(
.await
.map_err(|e| e.to_string())?;
let keybind_str = keybind.join("+");
app_handle
.emit("update-shortcut", keybind_str)
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("keybind_saved", Some(serde_json::json!({
"keybind": keybind_clone
})));
Ok(())
}
@ -61,17 +68,22 @@ pub async fn get_setting(
#[tauri::command]
pub async fn save_setting(
app_handle: tauri::AppHandle,
pool: tauri::State<'_, SqlitePool>,
key: String,
value: String,
) -> Result<(), String> {
sqlx::query("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)")
.bind(key)
.bind(key.clone())
.bind(value)
.execute(&*pool)
.await
.map_err(|e| e.to_string())?;
let _ = app_handle.track_event("setting_saved", Some(serde_json::json!({
"key": key
})));
Ok(())
}

View file

@ -7,15 +7,19 @@ mod api;
mod db;
mod utils;
use sqlx::sqlite::SqlitePoolOptions;
use std::fs;
use tauri::Manager;
use tauri::WebviewUrl;
use tauri::WebviewWindow;
use sqlx::sqlite::SqlitePoolOptions;
use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_prevent_default::Flags;
use tauri_plugin_aptabase::{EventTracker, InitOptions};
fn main() {
let runtime = tokio::runtime::Runtime::new().expect("Failed to create Tokio runtime");
let _guard = runtime.enter();
tauri::Builder::default()
.plugin(tauri_plugin_clipboard::init())
.plugin(tauri_plugin_os::init())
@ -23,6 +27,19 @@ fn main() {
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_updater::Builder::default().build())
.plugin(tauri_plugin_aptabase::Builder::new("A-SH-8937252746")
.with_options(InitOptions {
host: Some("https://aptabase.pandadev.net".to_string()),
flush_interval: None,
})
.with_panic_hook(Box::new(|client, info, msg| {
let location = info.location().map(|loc| format!("{}:{}:{}", loc.file(), loc.line(), loc.column())).unwrap_or_else(|| "".to_string());
let _ = client.track_event("panic", Some(serde_json::json!({
"info": format!("{} ({})", msg, location),
})));
}))
.build())
.plugin(tauri_plugin_autostart::init(
MacosLauncher::LaunchAgent,
Some(vec![]),
@ -85,6 +102,8 @@ fn main() {
utils::commands::center_window_on_current_monitor(&main_window);
main_window.hide()?;
let _ = app.track_event("app_started", None);
tauri::async_runtime::spawn(async move {
api::updater::check_for_updates(app_handle).await;
});