Cotton code
432 lines · 17.7 KB · RustRaw
//! Apple Health's export (Health → your picture → Export All Health Data)://! an `export.zip` holding `apple_health_export/export.xml`, read as a//! stream, so a file of millions of records costs a few days' tallies of//! memory, never the file.//!//! What it keeps is what Cotton Health keeps from HealthKit, through the//! same catalogue and the same rows: each catalogue metric folded per day,//! the workouts, and the point measurements (weight, blood pressure paired//! from its two records, glucose, temperature). Everything else in the//! file (the raw heart-rate stream, routes, the `Me` element, clinical//! records, ECGs, activity rings) is passed over unread. A sample in a unit//! the catalogue does not know is counted in `skipped`, never guessed.//!//! Records inside a `Correlation` are often also written at the top level;//! each record is taken once.use std::collections::{BTreeMap, HashSet};use std::io::{BufRead, Read};use quick_xml::events::{BytesStart, Event};use super::catalog::{self, Dimension};use super::fold::{fold_intervals, order, CategoryValue, Interval, QuantityDays};use super::rows::{instant, DayRow, Instant, MeasurementRow, Source, WorkoutRow};use crate::import::zip::{list_zip_entries_ranged, zip_entry_data_range, ZipEntry, ZipError, ZipRangeReader};/// What an export holds, as rows.#[derive(Debug, Default)]pub struct Export {    pub days: Vec<DayRow>,    pub workouts: Vec<WorkoutRow>,    pub measurements: Vec<MeasurementRow>,    /// Records read whose type Cotton Health keeps.    pub read: usize,    /// Kept types' records left out: a unit not known, a time or value that    /// does not read, a blood pressure missing its other half.    pub skipped: usize,}#[derive(Debug, Clone, PartialEq, Eq)]pub enum ExportError {    /// The archive holds no `export.xml`.    NoExport,    Zip(ZipError),    /// The XML does not read (its position and the reader's words).    Xml(String),}impl std::fmt::Display for ExportError {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        match self {            ExportError::NoExport => f.write_str("This archive holds no export.xml: it is not an Apple Health export."),            ExportError::Zip(error) => error.fmt(f),            ExportError::Xml(why) => write!(f, "The export does not read: {why}"),        }    }}impl std::error::Error for ExportError {}type Attributes = BTreeMap<String, String>;fn attributes(element: &BytesStart<'_>) -> Attributes {    element        .attributes()        .flatten()        .filter_map(|attribute| {            let key = String::from_utf8(attribute.key.as_ref().to_vec()).ok()?;            let value = cotton_rules::xml_text::attribute_value(&attribute)?;            Some((key, value))        })        .collect()}fn number(attrs: &Attributes, key: &str) -> Option<f64> {    attrs.get(key)?.trim().parse::<f64>().ok().filter(|value| value.is_finite())}/// A record met, with what its children said (a glucose reading's meal).struct Record {    attrs: Attributes,    meal: Option<String>,}/// A workout met, with its statistics children.struct Workout {    attrs: Attributes,    stats: Vec<Attributes>,}#[derive(Default)]struct Reading {    days: QuantityDays,    intervals: Vec<Interval>,    workouts: Vec<WorkoutRow>,    measurements: Vec<MeasurementRow>,    pressure: BTreeMap<(i64, String), (Option<f64>, Option<f64>, Instant)>,    seen: HashSet<(String, String, String, String, String)>,    read: usize,    skipped: usize,}/// A category type a day's metric is folded from (sleep, mindful minutes, a count of events…).fn kept_category(kind: &str) -> bool {    catalog::METRICS.iter().any(|metric| metric.healthkit == kind && metric.healthkit_unit.is_empty())}fn kept_type(kind: &str) -> bool {    catalog::quantity_metric(kind).is_some() || kept_category(kind) || catalog::MEASURES.iter().any(|measure| measure.healthkit == kind)}/// HealthKit's `HKBloodGlucoseMealTime`: 1 before a meal, 2 after.fn meal_word(value: &str) -> Option<String> {    match value.trim() {        "1" => Some("before_meal".into()),        "2" => Some("after_meal".into()),        _ => None,    }}impl Reading {    fn record(&mut self, record: Record) {        let attrs = &record.attrs;        let Some(kind) = attrs.get("type").map(String::as_str) else { return };        if !kept_type(kind) {            return;        }        let field = |key: &str| attrs.get(key).cloned().unwrap_or_default();        if !self.seen.insert((field("type"), field("sourceName"), field("startDate"), field("endDate"), field("value"))) {            return;        }        self.read += 1;        let (Some(start), Some(end)) = (attrs.get("startDate").and_then(|at| instant(at)), attrs.get("endDate").and_then(|at| instant(at))) else {            self.skipped += 1;            return;        };        let device = attrs.get("sourceName").cloned();        if kept_category(kind) {            let value = attrs.get("value").cloned().unwrap_or_default();            let value = value.parse::<i64>().map(CategoryValue::Raw).unwrap_or(CategoryValue::Word(value));            self.intervals.push(Interval { healthkit: kind.to_string(), value, start, end, device });            return;        }        let unit = attrs.get("unit").map(String::as_str).unwrap_or_default();        let Some(raw) = number(attrs, "value") else {            self.skipped += 1;            return;        };        let mut used = false;        if let Some(metric) = catalog::quantity_metric(kind) {            match catalog::canonical(metric.dimension, raw, unit) {                Some(value) => {                    self.days.add(metric, &start.day, device.as_deref().unwrap_or_default(), start.ms, value);                    used = true;                }                None => {                    self.skipped += 1;                    return;                }            }        }        match kind {            catalog::SYSTOLIC | catalog::DIASTOLIC => {                let Some(value) = catalog::canonical(Dimension::Pressure, raw, unit) else { return };                let held = self.pressure.entry((start.ms, device.clone().unwrap_or_default())).or_insert((None, None, start.clone()));                if kind == catalog::SYSTOLIC {                    held.0 = Some(value);                } else {                    held.1 = Some(value);                }            }            catalog::BODY_MASS | catalog::GLUCOSE | catalog::TEMPERATURE => {                let measure = catalog::MEASURES.iter().find(|measure| measure.healthkit == kind).expect("a catalogue measure");                let Some(value) = catalog::canonical(measure.dimension, raw, unit) else {                    if !used {                        self.skipped += 1;                    }                    return;                };                self.measurements.push(MeasurementRow {                    kind: measure.kind,                    measured_ms: start.ms,                    day: start.day.clone(),                    value,                    second: None,                    unit: measure.unit,                    context: if kind == catalog::GLUCOSE { record.meal.clone() } else { None },                    device,                    sample: None,                    source: Source::Export,                });            }            _ => {}        }    }    fn workout(&mut self, workout: Workout) {        let attrs = &workout.attrs;        let (Some(start), Some(end)) = (attrs.get("startDate").and_then(|at| instant(at)), attrs.get("endDate").and_then(|at| instant(at))) else {            self.skipped += 1;            return;        };        self.read += 1;        let kind = catalog::workout_kind_of_word(attrs.get("workoutActivityType").map(String::as_str).unwrap_or_default());        let minutes = number(attrs, "duration")            .and_then(|duration| catalog::canonical(Dimension::Duration, duration, attrs.get("durationUnit").map(String::as_str).unwrap_or("min")))            .unwrap_or((end.ms - start.ms) as f64 / 60_000.0);        let stat = |kind: &str| workout.stats.iter().find(|stat| stat.get("type").map(String::as_str) == Some(kind));        let summed = |attr: &str, unit_attr: &str, dimension: Dimension, types: &[&str]| -> Option<f64> {            if let Some(value) = number(attrs, attr) {                return catalog::canonical(dimension, value, attrs.get(unit_attr).map(String::as_str).unwrap_or_default());            }            types.iter().find_map(|kind| {                let stat = stat(kind)?;                catalog::canonical(dimension, number(stat, "sum")?, stat.get("unit").map(String::as_str).unwrap_or_default())            })        };        let distance = summed(            "totalDistance",            "totalDistanceUnit",            Dimension::Length,            &["HKQuantityTypeIdentifierDistanceWalkingRunning", "HKQuantityTypeIdentifierDistanceCycling", "HKQuantityTypeIdentifierDistanceSwimming", "HKQuantityTypeIdentifierDistanceWheelchair"],        )        .filter(|metres| *metres > 0.0);        let energy = summed("totalEnergyBurned", "totalEnergyBurnedUnit", Dimension::Energy, &["HKQuantityTypeIdentifierActiveEnergyBurned"]).filter(|kcal| *kcal > 0.0);        let heart = stat(catalog::HEART_RATE);        let rate = |key: &str| heart.and_then(|stat| catalog::canonical(Dimension::Rate, number(stat, key)?, stat.get("unit").map(String::as_str).unwrap_or("count/min")));        self.workouts.push(WorkoutRow {            kind,            started_ms: start.ms,            ended_ms: end.ms,            day: start.day.clone(),            minutes,            distance_m: distance,            energy_kcal: energy,            heart_rate_avg: rate("average"),            heart_rate_max: rate("maximum"),            device: attrs.get("sourceName").cloned(),            sample: None,            source: Source::Export,        });    }    fn finish(mut self) -> Export {        for ((_, device), (systolic, diastolic, at)) in std::mem::take(&mut self.pressure) {            match (systolic, diastolic) {                (Some(systolic), Some(diastolic)) => self.measurements.push(MeasurementRow {                    kind: "blood_pressure",                    measured_ms: at.ms,                    day: at.day.clone(),                    value: systolic,                    second: Some(diastolic),                    unit: "mmHg",                    context: None,                    device: Some(device).filter(|device| !device.is_empty()),                    sample: None,                    source: Source::Export,                }),                _ => self.skipped += 1,            }        }        let mut days = self.days.rows(Source::Export);        days.extend(fold_intervals(&self.intervals, Source::Export));        order(&mut days);        self.workouts.sort_by_key(|workout| workout.started_ms);        self.measurements.sort_by(|a, b| a.measured_ms.cmp(&b.measured_ms).then(a.kind.cmp(b.kind)));        Export { days, workouts: self.workouts, measurements: self.measurements, read: self.read, skipped: self.skipped }    }}/// Read an `export.xml` from `input`, a stream.pub fn read_export_xml<B: BufRead>(input: B) -> Result<Export, ExportError> {    let mut reader = quick_xml::Reader::from_reader(input);    reader.config_mut().trim_text(true);    let mut buf = Vec::new();    let mut reading = Reading::default();    // The element being gathered: a record (its metadata children) or a    // workout (its statistics), and whether it sits in a correlation.    let mut record: Option<Record> = None;    let mut workout: Option<Workout> = None;    loop {        let event = reader.read_event_into(&mut buf).map_err(|error| ExportError::Xml(format!("at byte {}: {error}", reader.buffer_position())))?;        match event {            Event::Eof => break,            Event::Start(element) | Event::Empty(element) if element.name().as_ref() == b"MetadataEntry" => {                let attrs = attributes(&element);                if let (Some(record), Some("HKBloodGlucoseMealTime")) = (record.as_mut(), attrs.get("key").map(String::as_str)) {                    record.meal = attrs.get("value").and_then(|value| meal_word(value));                }            }            Event::Start(element) => match element.name().as_ref() {                b"Record" => record = Some(Record { attrs: attributes(&element), meal: None }),                b"Workout" => workout = Some(Workout { attrs: attributes(&element), stats: Vec::new() }),                _ => {}            },            Event::Empty(element) => match element.name().as_ref() {                b"Record" => reading.record(Record { attrs: attributes(&element), meal: None }),                b"Workout" => reading.workout(Workout { attrs: attributes(&element), stats: Vec::new() }),                b"WorkoutStatistics" => {                    if let Some(workout) = workout.as_mut() {                        workout.stats.push(attributes(&element));                    }                }                _ => {}            },            Event::End(element) => match element.name().as_ref() {                b"Record" => {                    if let Some(done) = record.take() {                        reading.record(done);                    }                }                b"Workout" => {                    if let Some(done) = workout.take() {                        reading.workout(done);                    }                }                _ => {}            },            _ => {}        }        buf.clear();    }    Ok(reading.finish())}/// The archive's `export.xml` (never `export_cda.xml`, the clinical copy).pub fn export_entry<R: ZipRangeReader + ?Sized>(zip: &R) -> Result<ZipEntry, ExportError> {    let entries = list_zip_entries_ranged(zip).map_err(ExportError::Zip)?;    entries        .into_iter()        .filter(|entry| entry.name == "export.xml" || entry.name.ends_with("/export.xml"))        .min_by_key(|entry| entry.name.len())        .ok_or(ExportError::NoExport)}/// Read an `export.zip` through ranged reads: its `export.xml` is inflated/// as it is parsed, a window at a time.pub fn read_export_zip<R: ZipRangeReader + ?Sized>(zip: &R) -> Result<Export, ExportError> {    let entry = export_entry(zip)?;    let range = zip_entry_data_range(zip, &entry).map_err(ExportError::Zip)?;    let stream = EntryStream {        zip,        offset: range.offset,        end: range.offset + range.length,        input: Vec::new(),        at: 0,        state: (entry.method == 8).then(|| miniz_oxide::inflate::stream::InflateState::new_boxed(miniz_oxide::DataFormat::Raw)),        done: false,    };    read_export_xml(std::io::BufReader::with_capacity(1 << 16, stream))}/// How much of the archive one ranged read takes.const WINDOW: u64 = 1 << 20;/// One zip entry's bytes as a stream: stored entries as they are, deflated/// ones inflated a window at a time.struct EntryStream<'a, R: ZipRangeReader + ?Sized> {    zip: &'a R,    offset: u64,    end: u64,    input: Vec<u8>,    at: usize,    state: Option<Box<miniz_oxide::inflate::stream::InflateState>>,    done: bool,}impl<R: ZipRangeReader + ?Sized> EntryStream<'_, R> {    fn fill(&mut self) -> std::io::Result<bool> {        if self.at < self.input.len() {            return Ok(true);        }        if self.offset >= self.end {            return Ok(false);        }        let length = WINDOW.min(self.end - self.offset);        self.input = self.zip.read(self.offset, length).map_err(|error| std::io::Error::other(error.to_string()))?;        if self.input.len() as u64 != length {            return Err(std::io::Error::other("the archive answered a short read"));        }        self.offset += length;        self.at = 0;        Ok(true)    }}impl<R: ZipRangeReader + ?Sized> Read for EntryStream<'_, R> {    fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {        use miniz_oxide::{MZError, MZFlush, MZStatus};        if out.is_empty() {            return Ok(0);        }        loop {            if self.done {                return Ok(0);            }            let more = self.fill()?;            let Some(state) = self.state.as_mut() else {                if !more {                    return Ok(0);                }                let n = out.len().min(self.input.len() - self.at);                out[..n].copy_from_slice(&self.input[self.at..self.at + n]);                self.at += n;                return Ok(n);            };            let last = self.offset >= self.end;            // Never `Finish`: miniz takes that as "the whole output fits in            // `out`", which a stream's window never does.            let result = miniz_oxide::inflate::stream::inflate(state, &self.input[self.at..], out, MZFlush::None);            self.at += result.bytes_consumed;            match result.status {                Ok(MZStatus::StreamEnd) => {                    self.done = true;                    return Ok(result.bytes_written);                }                Ok(_) | Err(MZError::Buf) => {                    if result.bytes_written > 0 {                        return Ok(result.bytes_written);                    }                    if result.bytes_consumed == 0 && self.at < self.input.len() {                        return Err(std::io::Error::other("the export would not inflate further"));                    }                    if last && self.at >= self.input.len() {                        return Err(std::io::Error::other("the export ends before its last byte"));                    }                }                Err(error) => return Err(std::io::Error::other(format!("the export would not inflate ({error:?})"))),            }        }    }}