Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions app/controllers/maps_controller.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class MapsController < ApplicationController
include MapListFilters

before_action :set_map, only: %i[show properties feature layer destroy copy]
before_action :set_map_mode, only: %i[show properties feature layer]
before_action :set_map, only: %i[show properties feature garmin_upload layer destroy copy]
before_action :set_map_mode, only: %i[show properties feature garmin_upload layer]
before_action :set_client_view, only: %i[show]
before_action :join, only: %i[show]
before_action :set_global_js_values, only: %i[show tutorial]
before_action :check_permissions, only: %i[show properties feature layer]
before_action :check_permissions, only: %i[show properties feature garmin_upload layer]
before_action :require_login, only: %i[my copy]
before_action :require_map_owner, only: %i[destroy]
# Visitors without login get no session cookie (ApplicationController#disable_session_cookies),
Expand Down Expand Up @@ -137,6 +137,26 @@ def feature
end
end

def garmin_upload
feature = @map.features.find(params["feature_id"])
head :not_found and return unless feature&.geometry&.dig("type") == "LineString"
head :unauthorized and return unless @user&.garmin_token
result, course_id = @user.upload_garmin_course(feature)
Yabeda.feature_exports.increment(format: "garmin")
render json: { result:, course_id: }
rescue OAuth2::Error => e
Rails.logger.warn "Garmin upload failed: #{e.response.status} #{e.response.body}"
# 401 from the course call, 400 invalid_grant from the token refresh: the user has to connect again
if e.response.status == 401 || e.code == "invalid_grant"
@user.update!(garmin_token: nil)
head :unauthorized
elsif e.response.status == 412
render json: { error: _("Allow courses for Mapforge in your Garmin Connect account") }, status: :forbidden
else
render json: { error: e.description.presence || e.response.body }, status: :bad_gateway
end
end

def layer
layer = @map.layers.find(params["layer_id"])
head :not_found and return unless layer
Expand Down
9 changes: 9 additions & 0 deletions app/controllers/sessions_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ def developer

def create
user_info = request.env["omniauth.auth"]
return connect_garmin(user_info.credentials) if user_info.provider == "garmin"
user = User.find_or_create_by(uid: user_info.uid, provider: user_info.provider)
user.update!(email: user_info.info.email, name: user_info.info.name, image: user_info.info.image)
# Make first user admin
Expand All @@ -30,4 +31,12 @@ def create
session[:user_id] = user.id
redirect_to return_to || my_path
end

private

def connect_garmin(credentials)
return redirect_to(login_path) unless @user
@user.save_garmin_token!(credentials)
redirect_to url_from(request.env["omniauth.origin"]) || my_path
end
end
31 changes: 31 additions & 0 deletions app/javascript/controllers/feature/modal_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,37 @@ export default class extends Controller {
}
}

async sendToGarmin (event) {
event.preventDefault()
dom.showElements('#preloader')
try {
const response = await fetch(event.currentTarget.dataset.url, {
method: 'POST',
headers: { 'X-CSRF-Token': window.gon.csrf_token }
})
if (response.ok) {
const { result, course_id: courseId } = await response.json()
const text = result === 'updated' ? window.__('Updated in Garmin Connect') : window.__('Sent to Garmin Connect')
const link = Object.assign(document.createElement('a'), {
href: 'https://connect.garmin.com/modern/course/' + encodeURIComponent(courseId),
target: '_blank',
rel: 'noopener',
textContent: text
})
status(courseId ? link : text, 'info', 'medium', 15000)
} else if (response.status === 401) {
status(window.__('Garmin Connect login expired, reload the page to connect again'), 'error')
} else {
const error = (await response.json().catch(() => ({}))).error
status(window.__('Error sending to Garmin Connect') + (error ? ': ' + error : ''), 'error')
}
} catch {
status(window.__('Error sending to Garmin Connect'), 'error')
} finally {
Comment thread
Copilot marked this conversation as resolved.
Resolved
dom.hideElements('#preloader')
}
}

animate () {
const feature = this.getSelectedFeature()
console.log('Animating ' + feature.id)
Expand Down
3 changes: 2 additions & 1 deletion app/javascript/helpers/status.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ let fadeInterval = null
export function status (text, status = 'info', size = 'medium', duration = 6000) {
console.log(`Status (${status}): ` + text)
functions.e('#status-message', e => {
e.innerHTML = text
// Text goes in as plain text, because messages can carry error text from other servers
text instanceof Node ? e.replaceChildren(text) : (e.textContent = text)
e.className = size
})
functions.e('#status-container', e => {
Expand Down
5 changes: 5 additions & 0 deletions app/javascript/maplibre/feature/details.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ export function showFeatureDetails (feature) {
dom.showElements('.feature-export')
setExportHref('#feature-export-geo a', feature, '.geojson', '.geojson')
setExportHref('#feature-export-gpx a', feature, '.gpx', '')
f.e('#feature-export-garmin', e => {
e.classList.toggle('hidden', feature.geometry.type !== 'LineString')
const link = e.querySelector('a')
if (link) link.dataset.url = link.dataset.url.replace(/feature\/[^/]*/, 'feature/' + feature.id)
})
}

document.querySelector('#feature-details-description').innerHTML = window.__('Loading description...')
Expand Down
74 changes: 74 additions & 0 deletions app/models/concerns/garmin_account.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
module GarminAccount
extend ActiveSupport::Concern

COURSE_PATH = "/training-api/courses/v1/course"

included do
field :garmin_token, type: Hash
# feature id => Garmin courseId, so a repeated send updates the course instead of adding one
field :garmin_course_ids, type: Hash, default: {}
field :garmin_lock, type: Hash
end

# Returns [:updated or :created, courseId]. A course deleted in Garmin Connect answers 404 and gets created again.
def upload_garmin_course(feature)
with_garmin_lock do
token = garmin_access_token
course = feature.to_garmin_course
course_id = reload.garmin_course_ids[feature.id.to_s]
next [ :updated, course_id ] if course_id && update_garmin_course(token, course_id, course)
created = token.post(COURSE_PATH, course_request(course)).parsed
# $set on the one key, a whole-hash write would drop mappings that other requests saved meanwhile.
# Mongoid #set with a dotted key writes the whole hash, too.
collection.update_one({ _id: id }, { "$set" => { "garmin_course_ids.#{feature.id}" => created["courseId"] } })
[ :created, created["courseId"] ]
end
end

def garmin_access_token
client = OAuth2::Client.new(ENV["GARMIN_CLIENT_ID"], ENV["GARMIN_CLIENT_SECRET"], GARMIN_CLIENT_OPTIONS)
token = OAuth2::AccessToken.from_hash(client, garmin_token)
return token unless token.expired?
token.refresh.tap { |fresh| save_garmin_token!(fresh) }
end

# Takes OmniAuth credentials or an OAuth2::AccessToken. OAuth2::AccessToken#to_hash is no
# option, its :mode symbol comes back from MongoDB as a string, which the gem does not accept.
def save_garmin_token!(token)
update!(garmin_token: { "access_token" => token.token, "refresh_token" => token.refresh_token,
"expires_at" => token.expires_at })
end

private

# Parallel sends of one feature would each create a course, so a user's sends run one at a time
# across all app workers. ponytail: no lock renewal, a send that runs longer than 60s loses it.
def with_garmin_lock
owner = SecureRandom.hex
50.times do
free = { "$or" => [ { garmin_lock: nil }, { "garmin_lock.until" => { "$lt" => Time.current } } ] }
claim = { "$set" => { garmin_lock: { "owner" => owner, "until" => 60.seconds.from_now } } }
next sleep(0.2) if collection.update_one({ _id: id }.merge(free), claim).modified_count.zero?
begin
return yield
ensure
collection.update_one({ _id: id, "garmin_lock.owner" => owner }, { "$unset" => { garmin_lock: "" } })
end
end
raise "Another Garmin Connect upload of this user is still running"
end

# A new hash per request: OAuth2::AccessToken merges the user's bearer token into these headers
def course_request(course)
{ body: course.to_json, headers: { "Content-Type" => "application/json" } }
end

# false when Garmin no longer has the course
def update_garmin_course(token, course_id, course)
token.put("#{COURSE_PATH}/#{course_id}", course_request(course.merge(courseId: course_id)))
true
rescue OAuth2::Error => e
raise unless e.response.status == 404
false
end
end
31 changes: 31 additions & 0 deletions app/models/feature.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,33 @@ def to_gpx
GPX::GeoJSON.convert_to_gpx(geojson_data: to_geojson.to_json)
end

# Body of the Garmin Courses API. Garmin requires distance and elevation totals, and points at
# most 100m apart, so long segments get interpolated points.
def to_garmin_course
coords = geometry["coordinates"]
points = [ garmin_point(coords.first) ]
distance = gain = loss = 0.0
factory = Mapforge::LineIndex::FACTORY
coords.each_cons(2) do |a, b|
segment = factory.point(a[0], a[1]).distance(factory.point(b[0], b[1]))
steps = (segment / 100).ceil
# Across the antimeridian, interpolate towards the end point shifted by 360 degrees, not the long way round
b = [ b[0] - 360 * ((b[0] - a[0]) / 360.0).round, *b[1..] ]
(1..steps).each do |i|
lon, *rest = a.zip(b).map { |x, y| x && y && x + (y - x) * i.fdiv(steps) }
points << garmin_point([ (lon + 180) % 360 - 180, *rest ])
end
distance += segment
climb = a[2] && b[2] ? b[2] - a[2] : 0
climb.positive? ? gain += climb : loss -= climb
end
{ courseName: properties["title"].presence || layer&.map&.name.presence || "Mapforge track",
description: properties["description"].presence,
distance:, elevationGain: gain, elevationLoss: loss, geoPoints: points,
activityType: properties.dig("route", "profile") == "bike" ? "ROAD_CYCLING" : "HIKING",
coordinateSystem: "WGS84" }.compact
end

# expects EPSG:4326 (WGS 84), the GeoJSON default
def self.from_collection(geojson)
(geojson["features"] || [ geojson ]).filter_map do |feature|
Expand All @@ -63,6 +90,10 @@ def coordinates(include_height: true)

private

def garmin_point((lon, lat, ele))
{ latitude: lat, longitude: lon, elevation: ele }.compact
end

def sanitize_coordinates
return unless geometry["coordinates"].is_a?(Array)
geometry["coordinates"] = compact_coordinates(geometry["coordinates"])
Expand Down
1 change: 1 addition & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ class User
include ActiveModel::Model
include Mongoid::Document
include Mongoid::Timestamps
include GarminAccount

scope :admin, -> { where(admin: true) }
scope :github, -> { where(provider: "github") }
Expand Down
12 changes: 12 additions & 0 deletions app/views/maps/modals/_feature.haml
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,17 @@
=link_to map_feature_gpx_path(id: @map.public_id, feature_id: 'feature_id'), download: "", title: _('Download as GPX'), data: { turbo: false, toggle: "tooltip", 'bs-placement': "bottom", 'bs-trigger': "hover" } do
%i.bi.bi-download
GPX
- if @user && ENV["GARMIN_CLIENT_ID"].present?
%span.feature-export#feature-export-garmin.ms-2.link.text-nowrap<
- if @user.garmin_token
%a{ href: '#', title: _('Send to Garmin Connect'), data: { action: "click->feature--modal#sendToGarmin", url: map_feature_garmin_path(id: @map.public_id, feature_id: 'feature_id'), toggle: "tooltip", 'bs-placement': "bottom", 'bs-trigger': "hover" } }
%i.bi.bi-cloud-upload
Garmin
- else
= form_tag('/auth/garmin', method: 'post', class: 'd-inline', data: { turbo: false }) do
= hidden_field_tag :origin, request.original_url
= button_tag class: 'btn btn-link p-0 link', title: _('Connect Garmin Connect to send tracks to your device') do
%i.bi.bi-cloud-upload
Garmin
/ %span#feature-animation.ms-2.link
/ %i.bi.bi-camera-reels{title: "Play animation", 'data-toggle': "tooltip", 'data-bs-placement': "bottom", 'data-bs-trigger': "hover", 'data-action': "click->feature--modal#animate"}
21 changes: 21 additions & 0 deletions config/initializers/omniauth.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,23 @@
# Garmin Connect Developer Program, OAuth 2.0 PKCE. Garmin expects the client secret in the
# request body, not as basic auth.
GARMIN_CLIENT_OPTIONS = {
site: "https://apis.garmin.com",
authorize_url: "https://connect.garmin.com/oauth2Confirm",
token_url: "https://diauth.garmin.com/di-oauth2-service/oauth/token",
auth_scheme: :request_body
}.freeze

module OmniAuth
module Strategies
# Not a login provider: it links a Garmin account to the logged-in user, see SessionsController
class Garmin < OmniAuth::Strategies::OAuth2
option :name, "garmin"
option :pkce, true
option :client_options, GARMIN_CLIENT_OPTIONS
end
end
end

# Redirect urls are in format: /auth/google_oauth2/callback
Rails.application.config.middleware.use OmniAuth::Builder do
provider :developer if Rails.env.local? || ENV["DEVELOPER_LOGIN_ENABLED"] == "true"
Expand All @@ -12,6 +32,7 @@
prompt: "select_account"
# https://www.openstreetmap.org/oauth2/applications
provider :osm_oauth2, ENV["OSM_CLIENT_ID"], ENV["OSM_CLIENT_SECRET"]
provider :garmin, ENV["GARMIN_CLIENT_ID"], ENV["GARMIN_CLIENT_SECRET"]
end

OmniAuth.config.request_validation_phase = OmniAuth::AuthenticityTokenProtection.new(key: :_csrf_token)
Expand Down
2 changes: 2 additions & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@
get "/:id/feature/:feature_id.geojson(/:name)" => "maps#feature", :as => :map_feature_geo, :constraints => { id: ID_PATTERN, feature_id: ID_PATTERN, name: NAME_PATTERN }, :defaults => { format: "geojson" }
get "/:id/feature/:feature_id.gpx(/:name)" => "maps#feature", :as => :map_feature_gpx, :constraints => { id: ID_PATTERN, feature_id: ID_PATTERN, name: NAME_PATTERN }, :defaults => { format: "gpx" }

post "/:id/feature/:feature_id/garmin" => "maps#garmin_upload", :as => :map_feature_garmin, :constraints => { id: ID_PATTERN, feature_id: ID_PATTERN }

post "" => "maps#create", :as => :create_map
post "/:id/copy" => "maps#copy", :as => :copy_map, :constraints => { id: ID_PATTERN }
delete "/:id" => "maps#destroy", :as => :destroy_map, :constraints => { id: ID_PATTERN }
Expand Down
Loading
Loading