Class: GitFit::Import::AppleHealth

Inherits:
Source::Base show all
Defined in:
lib/git_fit/import/apple_health.rb

Defined Under Namespace

Classes: HeartRateRecord

Constant Summary collapse

SKIPPED_SOURCE_PATTERNS =
[
  /\bStrava\b/i, /\bKeep\b/i, /\biGPSPORT\b/i,
  /\bXOSS\b/i, /\bXingZhe\b/i, /\bConnect\b/i
].freeze
APPLE_WATCH_PATTERN =
/Apple Watch/
DEFAULT_ZIP_PATH =
'data/import/apple_health/export.zip'
MIN_GPX_SPEED =
0.1

Instance Attribute Summary

Attributes inherited from Source::Base

#progress_reported

Instance Method Summary collapse

Methods inherited from Source::Base

#build_progress_info

Constructor Details

#initialize(config:, db:, activity_filter: nil, privacy: nil, time_budget: nil) ⇒ AppleHealth

Returns a new instance of AppleHealth.



27
28
29
30
31
32
33
34
# File 'lib/git_fit/import/apple_health.rb', line 27

def initialize(config:, db:, activity_filter: nil, privacy: nil, time_budget: nil)
  super
  @zip_path = @config['zip_path'] || DEFAULT_ZIP_PATH
  @heart_rate_index = nil
  @heart_rate_by_date = nil
  @skip_patterns = load_skip_sources
  @timezone_resolver = GitFit::Timezone::Resolver.new(config)
end

Instance Method Details

#authenticateObject



41
42
43
# File 'lib/git_fit/import/apple_health.rb', line 41

def authenticate
  true
end

#before_callObject



36
37
38
39
# File 'lib/git_fit/import/apple_health.rb', line 36

def before_call
  return false unless File.exist?(@zip_path)
  super
end

#callObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/git_fit/import/apple_health.rb', line 45

def call
  return 0 unless before_call
  return 0 unless authenticate
  ids = pending_ids
  return 0 if ids.nil? || ids.empty?

  total = ids.size
  processed = 0
  ids.each do |p|
    break if time_expired? && processed.positive?
    r = process_one(p)
    processed += 1 if r
    report_progress(processed, total, build_progress_info(r)) if r
  end

  processed
end

#pending_idsObject



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/git_fit/import/apple_health.rb', line 63

def pending_ids
  existing = existing_run_ids_set
  results = []
  hr_records = []
  @route_index = []
  zip = Zip::File.new(@zip_path)
  xml_entry = zip.find_entry('apple_health_export/export.xml')
  return results unless xml_entry

  io = xml_entry.get_input_stream
  buffer = ''
  in_workout = false
  route_buf = nil

  io.each_line do |line|
    if line.include?('HKQuantityTypeIdentifierHeartRate') && APPLE_WATCH_PATTERN.match?(line)
      hr = parse_hr_line(line)
      hr_records << hr if hr
    end

    if line.include?('<WorkoutRoute ')
      route_buf = line
    elsif route_buf
      route_buf << line
      if line.include?('</WorkoutRoute>')
        process_route_entry(route_buf)
        route_buf = nil
      end
    end

    if !in_workout
      if line.include?('<Workout ')
        in_workout = true
        buffer = line
      end
    else
      buffer << line
      if line.include?('</Workout>')
        process_workout_chunk(buffer, existing, results)
        buffer = ''
        in_workout = false
      end
    end
  end

  @heart_rate_index = hr_records.sort_by(&:time)

  @heart_rate_by_date = {}
  @heart_rate_index.each do |hr|
    date_key = hr.time.strftime('%Y-%m-%d')
    @heart_rate_by_date[date_key] ||= []
    @heart_rate_by_date[date_key] << hr
  end

  results
ensure
  zip&.close
  io&.close rescue nil
end

#process_one(pending) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# File 'lib/git_fit/import/apple_health.rb', line 123

def process_one(pending)
  raw_xml = pending[:raw_xml]
  run_id = pending[:run_id]
  source_name = pending[:source_name]
  stats = pending[:stats]
  meta = pending[:meta]
  route_paths = pending[:route_paths]
  start_date = pending[:start_date]
  end_date = pending[:end_date]
  duration = pending[:duration]
  duration_unit = pending[:duration_unit]
  workout_type = pending[:workout_type]

  FileUtils.mkdir_p(raw_dir)
  tmp = File.join(raw_dir, ".#{run_id}.xml.tmp")
  final = File.join(raw_dir, "#{run_id}.xml")
  File.write(tmp, raw_xml)
  File.rename(tmp, final)

  hr_avg = nil
  hr_max = nil
  if @heart_rate_index&.any?
    hr_avg, hr_max = correlate_heart_rate(start_date, end_date)
  end

  l2_points = nil
  polyline = nil
  elevation_gain = nil

  if route_paths&.any?
    gpx_l1_path = File.join(raw_dir, "#{run_id}.gpx")
    unless File.exist?(gpx_l1_path)
      begin
        zip = Zip::File.new(@zip_path)
        route_paths.each do |gpx_path|
          normalized = gpx_path.sub(%r{^/?}, 'apple_health_export/')
          entry = zip.find_entry(normalized)
          next unless entry
          data = entry.get_input_stream.read
          tmpp = File.join(raw_dir, ".#{run_id}.gpx.tmp")
          File.write(tmpp, data)
          File.rename(tmpp, gpx_l1_path)
          break
        end
      rescue StandardError => e
        $stderr.puts "AppleHealth: GPX extract error for #{run_id}: #{e.message}"
      ensure
        zip&.close
      end
    end

    l2_points = File.exist?(gpx_l1_path) ? parse_gpx_file(gpx_l1_path) : nil

    if l2_points&.any?
      FileUtils.mkdir_p(std_dir)
      std_data = l2_points.map { |pt|
        h = { latitude: pt[:lat], longitude: pt[:lng] }
        h[:altitude] = pt[:ele] if pt[:ele]
        h[:timestamp] = pt[:time] if pt[:time]
        h[:speed] = pt[:speed] if pt[:speed]
        h
      }
      tmp2 = File.join(std_dir, ".#{run_id}.json.tmp")
      final2 = File.join(std_dir, "#{run_id}.json")
      File.write(tmp2, JSON.generate(std_data))
      File.rename(tmp2, final2)

      coords = l2_points.map { |pt| [pt[:lat], pt[:lng]] }
      polyline = GitFit::Geo::Polyline.encode(coords)
      elevation_gain = elevation_gain_from_points(l2_points)
    end
  end

  title = build_title(workout_type, start_date)
  attrs = build_attrs(source_name, run_id, stats, meta, polyline, elevation_gain,
                      workout_type, start_date, end_date, duration, duration_unit,
                      hr_avg, hr_max)
  attrs[:title] = title

  if attrs[:start_date_local].nil? && l2_points&.any?
    first_pt = l2_points.first
    tz = @timezone_resolver.resolve(first_pt[:lat], first_pt[:lng])
    if tz && attrs[:start_date]
      attrs[:start_date_local] = apple_utc_to_local(attrs[:start_date], tz)
    end
  end

  upsert_activity(attrs)
  attrs
end

#raw_dirObject



218
219
220
# File 'lib/git_fit/import/apple_health.rb', line 218

def raw_dir
  File.join('data', 'raw', 'apple_health')
end

#raw_path(platform_id) ⇒ Object



226
227
228
# File 'lib/git_fit/import/apple_health.rb', line 226

def raw_path(platform_id)
  File.join(raw_dir, "#{platform_id}.xml")
end

#source_labelObject



214
215
216
# File 'lib/git_fit/import/apple_health.rb', line 214

def source_label
  'AppleHealth'
end

#std_dirObject



222
223
224
# File 'lib/git_fit/import/apple_health.rb', line 222

def std_dir
  File.join('data', 'std', 'apple_health')
end