pookie 0.1.0

Load cookies from web browsers
Documentation
use std::{env, path::PathBuf};

use eyre::{Context, Result, anyhow, bail};

use crate::{browser::mozilla::get_default_profile, config::Browser};

fn expand_glob_paths(path: PathBuf) -> Result<Vec<PathBuf>> {
    let mut paths: Vec<PathBuf> = Vec::new();

    if let Some(path_str) = path.to_str() {
        for entry in glob::glob(path_str)? {
            if entry.is_ok() {
                paths.push(entry?);
            }
        }
    }
    Ok(paths)
}

pub fn find_chrome_based_paths(config: &Browser) -> Result<(PathBuf, PathBuf)> {
    for path in &config.paths {
        // base paths
        let channels = config.channels.clone().unwrap_or(vec!["".to_string()]);
        for channel in channels {
            // channels
            let path = path.replace("{channel}", &channel);
            let db_path = expand_path(path.as_str())?;
            let glob_db_paths = expand_glob_paths(db_path)?;
            for db_path in glob_db_paths {
                // glob expanded paths
                if db_path.exists()
                    && let Some(parent) = db_path.parent()
                {
                    let key_path =
                        ["../../Local State", "../Local State", "Local State"]
                            .iter()
                            .map(|p| parent.join(p))
                            .find(|p| p.exists())
                            .unwrap_or_else(|| parent.join("Local State"))
                            .canonicalize()
                            .context("canonicalize")?;
                    log::debug!(
                        "Found chrome path {}, {}",
                        db_path.display(),
                        key_path.display()
                    );
                    return Ok((key_path, db_path));
                }
            }
        }
    }
    Err(anyhow!("can't find cookies file"))
}

pub fn find_mozilla_based_paths(config: &Browser) -> Result<PathBuf> {
    for path in &config.paths {
        // base paths
        let channels = config.channels.clone().unwrap_or(vec!["".to_string()]);
        for channel in channels {
            // channels
            let path = path.replace("{channel}", &channel);
            let firefox_path = expand_path(path.as_str())?;
            let glob_paths = expand_glob_paths(firefox_path)?;
            for path in glob_paths {
                // expanded glob paths
                let profiles_path = path.join("profiles.ini");
                let default_profile =
                    get_default_profile(profiles_path.as_path())
                        .unwrap_or_default();
                let db_path = path.join(default_profile).join("cookies.sqlite");
                if db_path.exists() {
                    log::debug!("Found mozilla path {}", db_path.display());
                    return Ok(db_path);
                }
            }
        }
    }

    bail!("Can't find cookies file")
}

#[cfg(target_os = "macos")]
pub fn find_safari_based_paths(config: &Browser) -> Result<PathBuf> {
    for path in &config.paths {
        // base paths
        let channels = config.channels.clone().unwrap_or(vec!["".to_string()]);
        for channel in channels {
            // channels
            let path = path.replace("{channel}", &channel);
            let safari_path = expand_path(path.as_str())?;
            let glob_paths = expand_glob_paths(safari_path)?;
            for path in glob_paths {
                // expanded glob paths
                if path.exists() {
                    log::debug!("Found safari path {}", path.display());
                    return Ok(path);
                }
            }
        }
    }
    bail!("Can't find cookies file")
}

#[cfg(target_os = "windows")]
pub fn find_ie_based_paths(config: &Browser) -> Result<PathBuf> {
    for path in &config.paths {
        // base paths
        let channels = config.channels.clone().unwrap_or(vec!["".to_string()]);
        for channel in channels {
            // channels

            let path = path.replace("{channel}", &channel);
            let path = expand_path(path.as_str())?;
            let glob_paths = expand_glob_paths(path)?;
            for path in glob_paths {
                // expanded glob paths
                if path.exists() {
                    log::debug!("Found IE path {}", path.display());
                    return Ok(path);
                }
            }
        }
    }

    bail!("Can't find cookies file")
}

#[cfg(target_os = "windows")]
pub fn expand_path(path: &str) -> Result<PathBuf> {
    let mut iter = path.split('%');
    let mut expanded_path = String::new();

    // Expand `%NAME%` to the env variable only if it is set
    while let Some(component) = iter.next() {
        expanded_path.push_str(component);

        let Some(placeholder) = iter.next() else {
            continue;
        };

        // Try to get the corresponding environment variable value
        expanded_path.push_str(if let Ok(var_value) = env::var(placeholder) {
            // Replace the placeholder with the environment variable value
            &var_value
        } else {
            placeholder
        });
    }

    // Convert the expanded path to a `PathBuf`
    Ok(PathBuf::from(expanded_path))
}

#[cfg(unix)]
pub fn expand_path(path: &str) -> Result<PathBuf> {
    // Replace ~ or $HOME with the actual home directory path
    let expanded_path = if let Some(remaining_path) = path
        .strip_prefix("~/")
        .or_else(|| path.strip_prefix("$HOME"))
        // Get the value of the HOME environment variable
        && let Some(home_dir) = env::home_dir()
    {
        home_dir.join(remaining_path)
    } else {
        PathBuf::from(path.to_string())
    };

    // Convert the expanded path to a PathBuf
    Ok(expanded_path)
}