Files
maptool/lib/maptool/livetrack_client.rb
T
randy b0c93d10d7
CI / check (push) Successful in 18s
CI / deploy (push) Successful in 12s
Detect a LiveTrack session ending the moment Garmin confirms it, not 30min later
Watched the session from the last two commits actually get saved:
Garmin updated its `end` field from the future 24h placeholder to
within a second of the last point's own time, immediately — much
faster than the recency-of-last-point fallback alone would have
noticed (that only flips after ACTIVE_WITHIN with no new points, so a
just-saved session with a last point seconds old would still read as
active for up to 30 more minutes).

Now checks end-already-in-the-past first (authoritative and near
instant when Garmin has set it), falling back to point recency only
when end still shows the future placeholder — the case an abandoned,
never-saved session never updates.
2026-09-20 16:55:57 +02:00

169 lines
6.9 KiB
Ruby

require "net/http"
require "json"
require "time"
module Maptool
# Fetches a Garmin LiveTrack session's track and metadata.
#
# There's no usable REST call for this: livetrack.garmin.com/api/v2/... is
# behind Cloudflare bot protection that 403s a plain HTTP client regardless
# of headers (checked — not just a missing User-Agent). The session page
# itself isn't blocked, though, and Garmin's Next.js frontend renders it
# server-side, embedding both the full track and the session's own details
# (as React Server Component data, via `self.__next_f.push(...)` calls in
# the HTML) rather than fetching them client-side. So: fetch the page, and
# pull both out of that instead of the API it would otherwise call.
class LiveTrackClient
class FetchError < StandardError; end
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36"
PUSH_PATTERN = /self\.__next_f\.push\((\[.*?\])\)<\/script>/m
Result = Struct.new(:points, :session, :course, keyword_init: true)
def self.fetch(session_id, token)
new.fetch(session_id, token)
end
# `points`: array of track point hashes (position/dateTime/speed/...).
# `session`: hash of session details (sessionName/start/end/...), or nil
# if that part wasn't found even though points were (seen in practice:
# session details are consistently present alongside points, but nothing
# here depends on that holding forever).
# `course`: the planned route (name/geoPoints), or nil — only present
# when the activity was actually started from a saved Garmin course
# (session["courseIds"] is how the page itself knows to fetch one; a
# plain unplanned activity has neither).
def fetch(session_id, token)
payloads = parse_payloads(fetch_html(session_id, token))
points = search(payloads) { |node| node["trackPoints"] if node["trackPoints"].is_a?(Array) }
raise FetchError, "no track points found (session invalid or expired?)" unless points
session = search(payloads) { |node| node if node["sessionName"] }
# First of possibly several — a LiveTrack session only ever follows
# the one course it was started from.
course = search(payloads) { |node| node["courses"].first if node["courses"].is_a?(Array) && !node["courses"].empty? }
Result.new(points: clean(points), session: clean(session), course: clean(course))
end
# Distance/duration/activity type come from the last track point (its
# totals are cumulative for the whole session), name/type from the
# session details — nil-safe throughout since either can be missing.
#
# "active": originally `session["end"].nil?`, on the assumption Garmin
# doesn't set `end` until the activity actually stops — disproven
# against a real still-recording session (2026-09-20): `end` was
# already non-nil, set to exactly `start + 24h`, the share link's own
# expiry, not an actual end time. Two signals now, both verified live
# against that same session:
#
# * `end` itself, once it's actually in the past — watched the same
# session update it from that 24h placeholder to within a second of
# the last point's own time, immediately after the activity was
# saved on the watch. Authoritative and near-instant when present,
# so this is checked first.
# * failing that (still showing the future placeholder — an abandoned
# session never gets saved, so `end` never moves), recency of the
# last track point: Garmin posts one roughly every
# `postTrackPointFrequency` seconds (~15, observed) while genuinely
# still recording, so one older than ACTIVE_WITHIN means signal was
# lost a while ago (same "looks ended until it isn't" behavior
# Garmin's own LiveTrack page shows in that case).
#
# Both must agree the session is live — `end` already in the past
# means stopped even if the last point is only seconds old (exactly
# the save-immediately-after-the-last-point case above).
ACTIVE_WITHIN = 30 * 60 # seconds
def self.summarize(result)
last = result.points.last || {}
session = result.session || {}
{
"session_name" => session["sessionName"],
"activity_type" => last["activityType"],
"distance_meters" => last["totalDistanceMeters"],
"duration_secs" => last["totalDurationSecs"],
"active" => active?(last["dateTime"], session["end"]),
"start" => session["start"],
"end" => session["end"],
}
end
def self.active?(last_point_time, session_end)
return false unless last_point_time
now = Time.now.utc
return false if session_end && Time.parse(session_end) <= now
Time.parse(last_point_time) > now - ACTIVE_WITHIN
rescue ArgumentError, TypeError
false
end
private
# The RSC payload serializes an absent field as the literal string
# "$undefined" (Next.js's flight protocol, not JSON's own undefined) —
# normalize that to nil so nothing downstream has to know about it.
def clean(node)
case node
when "$undefined" then nil
when Hash then node.transform_values { |value| clean(value) }
when Array then node.map { |value| clean(value) }
else node
end
end
def fetch_html(session_id, token)
uri = URI("https://livetrack.garmin.com/session/#{session_id}/token/#{token}")
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 15) do |http|
http.get(uri.request_uri, "User-Agent" => USER_AGENT)
end
raise FetchError, "unexpected response #{response.code}" unless response.is_a?(Net::HTTPSuccess)
response.body
rescue SocketError, Timeout::Error, OpenSSL::SSL::SSLError => e
raise FetchError, e.message
end
# Next.js streams several of these RSC payloads per page, each an
# independently-parseable `[lineId, "<json>"]` pair once its line-id
# prefix is stripped off.
def parse_payloads(html)
html.scan(PUSH_PATTERN).filter_map do |(raw)|
push = safe_parse(raw)
next unless push.is_a?(Array) && push[1].is_a?(String)
_line_id, json = push[1].split(":", 2)
json && safe_parse(json)
end
end
# Walks the payloads looking for a hash the block matches — the payload
# nests under some data-fetching library's own structure (React Query,
# at the time this was written) that isn't worth depending on the exact
# shape of.
def search(node, &block)
case node
when Hash
found = block.call(node)
return found if found
node.each_value { |value| (found = search(value, &block)) and return found }
nil
when Array
node.each { |value| (found = search(value, &block)) and return found }
nil
end
end
def safe_parse(json)
JSON.parse(json)
rescue JSON::ParserError
nil
end
end
end