From bfad49fe4fa9b6f92725278e2a8231808570ff0e Mon Sep 17 00:00:00 2001 From: Thomas Schmidt Date: Sun, 15 Nov 2026 00:38:11 +0100 Subject: [PATCH 1/6] Add sending tracks to Garmin Connect as courses Users link a Garmin account through OAuth 2.0 PKCE and send a track from the feature modal. A repeated send updates the same course, and Mapforge creates it again if the user deleted it. The success message links to the course in Garmin Connect. --- app/controllers/maps_controller.rb | 26 ++- app/controllers/sessions_controller.rb | 9 + .../controllers/feature/modal_controller.js | 24 +++ app/javascript/maplibre/feature/details.js | 4 + app/models/concerns/garmin_account.rb | 52 +++++ app/models/feature.rb | 27 +++ app/models/user.rb | 1 + app/views/maps/modals/_feature.haml | 12 ++ config/initializers/omniauth.rb | 21 ++ config/routes.rb | 2 + locale/app.pot | 192 ++++++++++-------- locale/de/app.po | 21 ++ spec/models/feature_spec.rb | 29 +++ spec/requests/maps_controller_spec.rb | 71 +++++++ 14 files changed, 406 insertions(+), 85 deletions(-) create mode 100644 app/models/concerns/garmin_account.rb diff --git a/app/controllers/maps_controller.rb b/app/controllers/maps_controller.rb index 927ff3452..c20ce01fc 100644 --- a/app/controllers/maps_controller.rb +++ b/app/controllers/maps_controller.rb @@ -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), @@ -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 = @user.upload_garmin_course(feature) + Yabeda.feature_exports.increment(format: "garmin") + render json: { result:, course_id: @user.garmin_course_ids[feature.id.to_s] } + 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 diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index 9ae743f26..04e1ae731 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -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 @@ -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 diff --git a/app/javascript/controllers/feature/modal_controller.js b/app/javascript/controllers/feature/modal_controller.js index dfc95e267..306a6a5dc 100644 --- a/app/javascript/controllers/feature/modal_controller.js +++ b/app/javascript/controllers/feature/modal_controller.js @@ -424,6 +424,30 @@ 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 url = 'https://connect.garmin.com/modern/course/' + encodeURIComponent(courseId) + status(courseId ? `${text}` : 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') + } + } finally { + dom.hideElements('#preloader') + } + } + animate () { const feature = this.getSelectedFeature() console.log('Animating ' + feature.id) diff --git a/app/javascript/maplibre/feature/details.js b/app/javascript/maplibre/feature/details.js index 1c42a5e45..46652ae10 100644 --- a/app/javascript/maplibre/feature/details.js +++ b/app/javascript/maplibre/feature/details.js @@ -128,6 +128,10 @@ 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') }) + f.e('#feature-export-garmin a', e => { + e.dataset.url = e.dataset.url.replace(/feature\/[^/]*/, 'feature/' + feature.id) + }) } document.querySelector('#feature-details-description').innerHTML = window.__('Loading description...') diff --git a/app/models/concerns/garmin_account.rb b/app/models/concerns/garmin_account.rb new file mode 100644 index 000000000..85a6fc575 --- /dev/null +++ b/app/models/concerns/garmin_account.rb @@ -0,0 +1,52 @@ +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: {} + end + + # Returns :updated or :created. A course deleted in Garmin Connect answers 404 and gets created again. + def upload_garmin_course(feature) + token = garmin_access_token + course = feature.to_garmin_course + course_id = garmin_course_ids[feature.id.to_s] + return :updated if course_id && update_garmin_course(token, course_id, course) + created = token.post(COURSE_PATH, course_request(course)).parsed + update!(garmin_course_ids: garmin_course_ids.merge(feature.id.to_s => created["courseId"])) + :created + 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 + + # 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 diff --git a/app/models/feature.rb b/app/models/feature.rb index cf4a4079e..533a7f602 100644 --- a/app/models/feature.rb +++ b/app/models/feature.rb @@ -50,6 +50,29 @@ 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 + vertexes = coords.map { |c| Mapforge::LineIndex::FACTORY.point(c[0], c[1]) } + coords.zip(vertexes).each_cons(2) do |(a, va), (b, vb)| + segment = va.distance(vb) + steps = (segment / 100).ceil + (1..steps).each do |i| + points << garmin_point(a.zip(b).map { |x, y| x && y && x + (y - x) * i.fdiv(steps) }) + end + distance += segment + climb = a[2] && b[2] ? b[2] - a[2] : 0 + climb.positive? ? gain += climb : loss -= climb + end + { courseName: properties["title"].presence || "Mapforge track", description: properties["desc"].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| @@ -63,6 +86,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"]) diff --git a/app/models/user.rb b/app/models/user.rb index 5bd620946..83724be18 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -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") } diff --git a/app/views/maps/modals/_feature.haml b/app/views/maps/modals/_feature.haml index e6fec04b0..25c54dc97 100644 --- a/app/views/maps/modals/_feature.haml +++ b/app/views/maps/modals/_feature.haml @@ -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"} diff --git a/config/initializers/omniauth.rb b/config/initializers/omniauth.rb index cc40ac0af..62fb8770b 100644 --- a/config/initializers/omniauth.rb +++ b/config/initializers/omniauth.rb @@ -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" @@ -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) diff --git a/config/routes.rb b/config/routes.rb index 526908afc..99e4b5d04 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -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 } diff --git a/locale/app.pot b/locale/app.pot index dd2d8640e..f20b63a99 100644 --- a/locale/app.pot +++ b/locale/app.pot @@ -8,8 +8,8 @@ msgid "" msgstr "" "Project-Id-Version: app 1.0.0\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-14 13:27+0100\n" -"PO-Revision-Date: 2026-11-14 13:27+0100\n" +"POT-Creation-Date: 2026-11-15 00:26+0100\n" +"PO-Revision-Date: 2026-11-15 00:26+0100\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" @@ -148,6 +148,10 @@ msgstr "" msgid "All" msgstr "" +#: ../app/controllers/maps_controller.rb:154 +msgid "Allow courses for Mapforge in your Garmin Connect account" +msgstr "" + #: ../app/views/maps/modals/feature/_edit_ui.haml:241 msgid "Applies in view mode. In edit mode, a click always selects the feature." msgstr "" @@ -164,7 +168,7 @@ msgstr "" msgid "Ascending" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:67 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:70 msgid "Asphalt" msgstr "" @@ -208,19 +212,19 @@ msgstr "" msgid "Bicycle Touring with Mapforge" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:262 +#: ../app/javascript/maplibre/styles/basemaps.js:263 msgid "Bicycle map with bike routes and trails" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:166 +#: ../app/javascript/maplibre/styles/basemaps.js:167 msgid "Bicycle map with cycle paths and bike routes" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:186 +#: ../app/javascript/maplibre/styles/basemaps.js:187 msgid "Bicycle map with cycle routes and height lines" msgstr "" -#: ../app/views/maps/modals/_settings.haml:58 ../app/javascript/maplibre/feature.js:79 +#: ../app/views/maps/modals/_settings.haml:58 ../app/javascript/maplibre/feature.js:78 msgid "Bicycle route" msgstr "" @@ -232,7 +236,7 @@ msgstr "" msgid "Big dots" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:100 +#: ../app/javascript/maplibre/styles/basemaps.js:101 msgid "Black and white map, good for printing" msgstr "" @@ -248,7 +252,7 @@ msgstr "" msgid "Border width:" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:230 +#: ../app/javascript/maplibre/styles/basemaps.js:231 msgid "Bright street map with clear roads and labels" msgstr "" @@ -296,7 +300,7 @@ msgstr "" msgid "Car" msgstr "" -#: ../app/views/maps/modals/_settings.haml:61 ../app/javascript/maplibre/feature.js:80 +#: ../app/views/maps/modals/_settings.haml:61 ../app/javascript/maplibre/feature.js:79 msgid "Car route" msgstr "" @@ -336,7 +340,7 @@ msgstr "" msgid "Click to toggle format" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:68 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 msgid "Cobblestone" msgstr "" @@ -348,11 +352,11 @@ msgstr "" msgid "Color:" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:238 +#: ../app/javascript/maplibre/styles/basemaps.js:239 msgid "Colorful street map for everyday use" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:69 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:72 msgid "Compacted gravel" msgstr "" @@ -364,7 +368,7 @@ msgstr "" msgid "Compass mode" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:68 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 msgid "Concrete" msgstr "" @@ -372,6 +376,10 @@ msgstr "" msgid "Configure Map" msgstr "" +#: ../app/views/maps/modals/_feature.haml:79 +msgid "Connect Garmin Connect to send tracks to your device" +msgstr "" + #: ../app/javascript/maplibre/controls/shared.js:141 msgid "Connection error" msgstr "" @@ -480,7 +488,7 @@ msgstr "" msgid "Custom raster layer" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:242 +#: ../app/javascript/maplibre/styles/basemaps.js:243 msgid "Dark map, easy on the eyes at night" msgstr "" @@ -528,11 +536,11 @@ msgstr "" msgid "Description" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:225 +#: ../app/javascript/maplibre/styles/basemaps.js:226 msgid "Detailed street map in the style of official German maps" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:231 +#: ../app/javascript/maplibre/styles/basemaps.js:232 msgid "Detailed street map with buildings and landmarks" msgstr "" @@ -544,7 +552,7 @@ msgstr "" msgid "Device Orientation not supported" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:70 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:73 msgid "Dirt" msgstr "" @@ -588,11 +596,11 @@ msgstr "" msgid "Dots" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:55 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:58 msgid "Downhill" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:56 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:59 msgid "Downhill (12-15%)" msgstr "" @@ -732,6 +740,10 @@ msgstr "" msgid "Error detecting location: %{message}" msgstr "" +#: ../app/javascript/controllers/feature/modal_controller.js:442 +msgid "Error sending to Garmin Connect" +msgstr "" + #: ../app/javascript/controllers/feature/edit_controller.js:82 ../app/javascript/controllers/feature/modal_controller.js:320 msgid "Error updating %{type}" msgstr "" @@ -748,11 +760,11 @@ msgstr "" msgid "Failed to copy" msgstr "" -#: ../app/javascript/maplibre/layers/layer.js:255 +#: ../app/javascript/maplibre/layers/layer.js:319 msgid "Failed to load layer %{name}" msgstr "" -#: ../app/javascript/maplibre/feature.js:76 +#: ../app/javascript/maplibre/feature.js:75 msgid "Feature" msgstr "" @@ -792,7 +804,7 @@ msgstr "" msgid "Find my location" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:69 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:72 msgid "Fine gravel" msgstr "" @@ -804,11 +816,11 @@ msgstr "" msgid "Fixed view" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:55 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:58 msgid "Flat" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:57 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:60 msgid "Flat (0%)" msgstr "" @@ -828,7 +840,7 @@ msgstr "" msgid "Free to try, no signup needed." msgstr "" -#: ../app/javascript/maplibre/feature/elevation.js:341 +#: ../app/javascript/maplibre/feature/elevation.js:367 msgid "Full track" msgstr "" @@ -844,11 +856,15 @@ msgstr "" msgid "Gallery" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:57 +#: ../app/javascript/controllers/feature/modal_controller.js:439 +msgid "Garmin Connect login expired, reload the page to connect again" +msgstr "" + +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:60 msgid "Gentle downhill (4-6%)" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:58 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:61 msgid "Gentle uphill (4-6%)" msgstr "" @@ -868,19 +884,19 @@ msgstr "" msgid "Go to feature" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:74 msgid "Grass" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:74 msgid "Grass paver" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:69 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:72 msgid "Gravel" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:239 +#: ../app/javascript/maplibre/styles/basemaps.js:240 msgid "Gray map in calm colors, your own data stands out" msgstr "" @@ -888,7 +904,7 @@ msgstr "" msgid "Grid" msgstr "" -#: ../app/javascript/maplibre/controls/level_control.js:7 ../app/javascript/maplibre/layers/geojson/route_extras.js:70 +#: ../app/javascript/maplibre/controls/level_control.js:7 ../app/javascript/maplibre/layers/geojson/route_extras.js:73 msgid "Ground" msgstr "" @@ -908,11 +924,11 @@ msgstr "" msgid "Hide layer" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:123 +#: ../app/javascript/maplibre/styles/basemaps.js:124 msgid "Hiking map with height lines and hill shadows" msgstr "" -#: ../app/javascript/maplibre/feature.js:81 +#: ../app/javascript/maplibre/feature.js:80 msgid "Hiking route" msgstr "" @@ -940,7 +956,7 @@ msgstr "" msgid "How to use the µlogger app to log your tracks from your phone." msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:70 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:73 msgid "Ice" msgstr "" @@ -1044,11 +1060,11 @@ msgstr "" msgid "Levels" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:234 +#: ../app/javascript/maplibre/styles/basemaps.js:235 msgid "Light street map with soft colors" msgstr "" -#: ../app/javascript/maplibre/feature.js:86 +#: ../app/javascript/maplibre/feature.js:85 msgid "Line" msgstr "" @@ -1080,11 +1096,11 @@ msgstr "" msgid "Load for this area" msgstr "" -#: ../app/javascript/maplibre/map.js:624 +#: ../app/javascript/maplibre/map.js:627 msgid "Loaded base map %{name}" msgstr "" -#: ../app/javascript/maplibre/feature/details.js:133 +#: ../app/javascript/maplibre/feature/details.js:137 msgid "Loading description..." msgstr "" @@ -1160,7 +1176,7 @@ msgstr "" msgid "Map settings" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:77 +#: ../app/javascript/maplibre/styles/basemaps.js:78 msgid "Map that looks like a watercolor painting" msgstr "" @@ -1168,7 +1184,7 @@ msgstr "" msgid "Map view updated" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:247 +#: ../app/javascript/maplibre/styles/basemaps.js:248 msgid "Map with its own hand-picked colors" msgstr "" @@ -1180,11 +1196,11 @@ msgstr "" msgid "Max. 5MB" msgstr "" -#: ../app/javascript/maplibre/map.js:397 +#: ../app/javascript/maplibre/map.js:400 msgid "Maximum zoom level %{zoom} reached" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:68 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 msgid "Metal" msgstr "" @@ -1192,15 +1208,15 @@ msgstr "" msgid "Midpoint deleted" msgstr "" -#: ../app/javascript/maplibre/map.js:401 +#: ../app/javascript/maplibre/map.js:404 msgid "Minimum zoom level %{zoom} reached" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:56 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:59 msgid "Moderate downhill (7-11%)" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:58 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:61 msgid "Moderate uphill (7-11%)" msgstr "" @@ -1320,7 +1336,7 @@ msgstr "" msgid "OpenStreetMap indoor" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:204 +#: ../app/javascript/maplibre/styles/basemaps.js:205 msgid "Outdoor map with strong colors, easy to read outside" msgstr "" @@ -1356,11 +1372,11 @@ msgstr "" msgid "Pattern" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:67 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:70 msgid "Paved" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:70 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:73 msgid "Paving stones" msgstr "" @@ -1368,19 +1384,19 @@ msgstr "" msgid "Pin" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:229 +#: ../app/javascript/maplibre/styles/basemaps.js:230 msgid "Plain light gray map, your own data stands out" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:241 +#: ../app/javascript/maplibre/styles/basemaps.js:242 msgid "Plain map with soft colors and few labels" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:257 +#: ../app/javascript/maplibre/styles/basemaps.js:258 msgid "Plain map, your own data stands out" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:254 +#: ../app/javascript/maplibre/styles/basemaps.js:255 msgid "Plain, easy to read street map" msgstr "" @@ -1416,7 +1432,7 @@ msgstr "" msgid "Please log in to upload images" msgstr "" -#: ../app/javascript/maplibre/feature.js:85 +#: ../app/javascript/maplibre/feature.js:84 msgid "Point" msgstr "" @@ -1424,7 +1440,7 @@ msgstr "" msgid "Point Mode: Click on the map to place a marker" msgstr "" -#: ../app/javascript/maplibre/feature.js:87 +#: ../app/javascript/maplibre/feature.js:86 msgid "Polygon" msgstr "" @@ -1592,7 +1608,7 @@ msgstr "" msgid "Routing with elevation profile" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:74 msgid "Sand" msgstr "" @@ -1600,15 +1616,15 @@ msgstr "" msgid "Satellite" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:263 +#: ../app/javascript/maplibre/styles/basemaps.js:264 msgid "Satellite photos with street names" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:221 ../app/javascript/maplibre/styles/basemaps.js:244 +#: ../app/javascript/maplibre/styles/basemaps.js:222 ../app/javascript/maplibre/styles/basemaps.js:245 msgid "Satellite photos with street names and places" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:260 +#: ../app/javascript/maplibre/styles/basemaps.js:261 msgid "Satellite photos without labels" msgstr "" @@ -1648,6 +1664,14 @@ msgstr "" msgid "Self-hosting guide" msgstr "" +#: ../app/views/maps/modals/_feature.haml:73 +msgid "Send to Garmin Connect" +msgstr "" + +#: ../app/javascript/controllers/feature/modal_controller.js:437 +msgid "Sent to Garmin Connect" +msgstr "" + #: ../app/views/maps/modals/_settings.haml:173 msgid "Set current view as default" msgstr "" @@ -1733,11 +1757,11 @@ msgstr "" msgid "Size:" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:57 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:60 msgid "Slight downhill (1-3%)" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:58 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:61 msgid "Slight uphill (1-3%)" msgstr "" @@ -1753,7 +1777,7 @@ msgstr "" msgid "Square" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:147 +#: ../app/javascript/maplibre/styles/basemaps.js:148 msgid "Standard OpenStreetMap with roads and places" msgstr "" @@ -1769,31 +1793,31 @@ msgstr "" msgid "Start for free" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:56 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:59 msgid "Steep downhill (>16%)" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:59 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:62 msgid "Steep uphill (>16%)" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:52 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:55 msgid "Steepness" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:255 +#: ../app/javascript/maplibre/styles/basemaps.js:256 msgid "Street map in the familiar OpenStreetMap look" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:256 +#: ../app/javascript/maplibre/styles/basemaps.js:257 msgid "Street map with 3D buildings" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:258 +#: ../app/javascript/maplibre/styles/basemaps.js:259 msgid "Street map with roads and places" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:259 +#: ../app/javascript/maplibre/styles/basemaps.js:260 msgid "Street map without street names" msgstr "" @@ -1821,7 +1845,7 @@ msgstr "" msgid "Supported formats: gpx, kml, kmz, geojson, mapforge json and images. WGS84 format, max. 2.5MB" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:64 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:67 msgid "Surface" msgstr "" @@ -1925,7 +1949,7 @@ msgstr "" msgid "Track added" msgstr "" -#: ../app/javascript/maplibre/feature/elevation.js:144 +#: ../app/javascript/maplibre/feature/elevation.js:146 msgid "Track elevation chart" msgstr "" @@ -1969,11 +1993,11 @@ msgstr "" msgid "Undone: %{type}" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:67 ../app/javascript/maplibre/layers/geojson/route_extras.js:143 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:70 ../app/javascript/maplibre/layers/geojson/route_extras.js:146 msgid "Unknown" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:67 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:70 msgid "Unpaved" msgstr "" @@ -1993,11 +2017,15 @@ msgstr "" msgid "Updated %{time} ago" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:55 +#: ../app/javascript/controllers/feature/modal_controller.js:437 +msgid "Updated in Garmin Connect" +msgstr "" + +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:58 msgid "Uphill" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:59 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:62 msgid "Uphill (12-15%)" msgstr "" @@ -2037,7 +2065,7 @@ msgstr "" msgid "View your map with mountains and valleys" msgstr "" -#: ../app/views/maps/modals/_feature.haml:55 ../app/javascript/maplibre/feature/elevation.js:341 +#: ../app/views/maps/modals/_feature.haml:55 ../app/javascript/maplibre/feature/elevation.js:367 msgid "Visible section" msgstr "" @@ -2053,7 +2081,7 @@ msgstr "" msgid "Waypoint added" msgstr "" -#: ../app/javascript/maplibre/feature/elevation.js:240 +#: ../app/javascript/maplibre/feature/elevation.js:233 msgid "Waypoint:" msgstr "" @@ -2069,11 +2097,11 @@ msgstr "" msgid "Wikipedia articles" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:261 +#: ../app/javascript/maplibre/styles/basemaps.js:262 msgid "Winter map with snow and ski slopes" msgstr "" -#: ../app/javascript/maplibre/styles/basemaps.js:240 +#: ../app/javascript/maplibre/styles/basemaps.js:241 msgid "Winter map with snow on the mountains" msgstr "" @@ -2081,11 +2109,11 @@ msgstr "" msgid "With this link, users can modify the map, add layers, and make changes." msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:68 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 msgid "Wood" msgstr "" -#: ../app/javascript/maplibre/layers/geojson/route_extras.js:71 +#: ../app/javascript/maplibre/layers/geojson/route_extras.js:74 msgid "Woodchips" msgstr "" diff --git a/locale/de/app.po b/locale/de/app.po index 1000f6107..c3ba07e6c 100644 --- a/locale/de/app.po +++ b/locale/de/app.po @@ -115,6 +115,9 @@ msgstr "Erweiterte Objektgestaltung" msgid "All" msgstr "Alle" +msgid "Allow courses for Mapforge in your Garmin Connect account" +msgstr "Erlaube Strecken für Mapforge in deinem Garmin Connect Konto" + msgid "Applies in view mode. In edit mode, a click always selects the feature." msgstr "Gilt im Ansichtsmodus. Im Bearbeitungsmodus wählt ein Klick immer das Objekt aus." @@ -283,6 +286,9 @@ msgstr "Beton" msgid "Configure Map" msgstr "Karte einrichten" +msgid "Connect Garmin Connect to send tracks to your device" +msgstr "Verbinde Garmin Connect, um Tracks an dein Gerät zu senden" + msgid "Connection error" msgstr "Verbindungsfehler" @@ -553,6 +559,9 @@ msgstr "Fehler beim Umwandeln des Tracks: %{message}" msgid "Error detecting location: %{message}" msgstr "Fehler beim Ermitteln des Standorts: %{message}" +msgid "Error sending to Garmin Connect" +msgstr "Fehler beim Senden an Garmin Connect" + msgid "Error updating %{type}" msgstr "Fehler beim Aktualisieren von %{type}" @@ -637,6 +646,9 @@ msgstr "GPS-Position" msgid "Gallery" msgstr "Galerie" +msgid "Garmin Connect login expired, reload the page to connect again" +msgstr "Garmin Connect Anmeldung abgelaufen, lade die Seite neu, um dich erneut zu verbinden" + msgid "Gentle downhill (4-6%)" msgstr "Leichtes Gefälle (4-6 %)" @@ -1240,6 +1252,12 @@ msgstr "Selbst hostbar" msgid "Self-hosting guide" msgstr "Self-Hosting-Anleitung" +msgid "Send to Garmin Connect" +msgstr "An Garmin Connect senden" + +msgid "Sent to Garmin Connect" +msgstr "An Garmin Connect gesendet" + msgid "Set current view as default" msgstr "Aktuelle Ansicht als Standard setzen" @@ -1499,6 +1517,9 @@ msgstr "Ebene aktualisieren" msgid "Updated %{time} ago" msgstr "Aktualisiert vor %{time}" +msgid "Updated in Garmin Connect" +msgstr "In Garmin Connect aktualisiert" + msgid "Uphill" msgstr "Bergauf" diff --git a/spec/models/feature_spec.rb b/spec/models/feature_spec.rb index baf60027e..09491bebc 100644 --- a/spec/models/feature_spec.rb +++ b/spec/models/feature_spec.rb @@ -12,6 +12,35 @@ end end + describe "#to_garmin_course" do + let(:feature) { build(:feature, :line_string_with_elevation, title: "Hike") } + let(:course) { feature.to_garmin_course } + + it "sums the climb and the descent" do + expect(course).to include(courseName: "Hike", elevationGain: 50.0, elevationLoss: 60.0, + activityType: "HIKING", coordinateSystem: "WGS84") + end + + it "keeps the vertexes in lat/lon order with elevation" do + expect(course[:geoPoints].first).to eq(latitude: 49.46, longitude: 11.06, elevation: 300) + expect(course[:geoPoints].last).to include(latitude: be_within(1e-9).of(49.435), elevation: be_within(1e-9).of(290)) + end + + it "keeps points at most 100m apart" do + factory = RGeo::Geographic.spherical_factory + gaps = course[:geoPoints].each_cons(2).map do |a, b| + factory.point(a[:longitude], a[:latitude]).distance(factory.point(b[:longitude], b[:latitude])) + end + expect(gaps.max).to be <= 100 + expect(gaps.sum).to be_within(1).of(course[:distance]) + end + + it "uses a cycling course for bike routes" do + feature.properties["route"] = { "profile" => "bike" } + expect(course[:activityType]).to eq("ROAD_CYCLING") + end + end + describe "#to_gpx" do it "exports valid gpx" do feature = described_class.create(type: "Feature", geometry: { "type" => "Point", "coordinates" => [ 11.0557138, 49.4731983 ] }) diff --git a/spec/requests/maps_controller_spec.rb b/spec/requests/maps_controller_spec.rb index db1891b78..fda4c7513 100644 --- a/spec/requests/maps_controller_spec.rb +++ b/spec/requests/maps_controller_spec.rb @@ -68,6 +68,77 @@ end end + describe "#garmin_upload" do + let(:user) { create(:user, garmin_token: { "access_token" => "abc", "expires_at" => 1.hour.from_now.to_i }) } + let!(:feature) { create(:feature, :line_string, title: "Track", layer: map.layers.first) } + let(:path) { map_feature_garmin_path(id: map.public_id, feature_id: feature.id) } + + let(:created) { instance_double(OAuth2::Response, parsed: { "courseId" => 43 }) } + + def garmin_error(status, body = "") + OAuth2::Error.new(OAuth2::Response.new(Faraday::Response.new(status:, body:))) + end + + before { sign_in(user) } + + # Stubbed on the client, so the token still adds its Authorization header to the request + it "creates the course and remembers its id" do + allow_any_instance_of(OAuth2::Client).to receive(:request) + .with(:post, "/training-api/courses/v1/course", + hash_including(body: feature.to_garmin_course.to_json, + headers: { "Content-Type" => "application/json", "Authorization" => "Bearer abc" })) + .and_return(created) + expect { post path }.to change { Yabeda.feature_exports.get(format: "garmin").to_i }.by(1) + expect(response.parsed_body).to eq("result" => "created", "course_id" => 43) + expect(user.reload.garmin_course_ids).to eq(feature.id.to_s => 43) + end + + it "updates a course that was sent before" do + user.update!(garmin_course_ids: { feature.id.to_s => 42 }) + expect_any_instance_of(OAuth2::Client).to receive(:request).once + .with(:put, "/training-api/courses/v1/course/42", + hash_including(body: feature.to_garmin_course.merge(courseId: 42).to_json)) + post path + expect(response.parsed_body).to eq("result" => "updated", "course_id" => 42) + end + + it "creates the course again when it was deleted in Garmin Connect" do + user.update!(garmin_course_ids: { feature.id.to_s => 42 }) + allow_any_instance_of(OAuth2::AccessToken).to receive(:put).and_raise(garmin_error(404)) + allow_any_instance_of(OAuth2::AccessToken).to receive(:post).and_return(created) + post path + expect(response.parsed_body).to eq("result" => "created", "course_id" => 43) + expect(user.reload.garmin_course_ids).to eq(feature.id.to_s => 43) + end + + it "refuses a user without Garmin connection" do + user.update!(garmin_token: nil) + post path + expect(response).to have_http_status(:unauthorized) + end + + it "drops a token that Garmin rejects" do + allow_any_instance_of(OAuth2::AccessToken).to receive(:post).and_raise(garmin_error(401)) + post path + expect(response).to have_http_status(:unauthorized) + expect(user.reload.garmin_token).to be_nil + end + + it "reports a missing course permission" do + allow_any_instance_of(OAuth2::AccessToken).to receive(:post).and_raise(garmin_error(412)) + post path + expect(response).to have_http_status(:forbidden) + expect(user.reload.garmin_token).to be_present + end + + it "reports other Garmin errors" do + allow_any_instance_of(OAuth2::AccessToken).to receive(:post).and_raise(garmin_error(400, "too many points")) + post path + expect(response).to have_http_status(:bad_gateway) + expect(user.reload.garmin_token).to be_present + end + end + describe "#show (preloads)" do it "preloads the map modules, and the draw modules only in edit mode" do get map_path(id: map.public_id) From 748b8d8b0f45f694bbb5286640885fe773c1a53e Mon Sep 17 00:00:00 2001 From: Thomas Schmidt Date: Sun, 15 Nov 2026 23:15:43 +0100 Subject: [PATCH 2/6] implement review feedback --- app/controllers/maps_controller.rb | 4 +- .../controllers/feature/modal_controller.js | 11 +++++- app/javascript/helpers/status.js | 3 +- app/javascript/maplibre/feature/details.js | 7 ++-- app/models/concerns/garmin_account.rb | 39 +++++++++++++++---- app/models/feature.rb | 11 ++++-- spec/models/feature_spec.rb | 21 +++++++--- spec/requests/maps_controller_spec.rb | 9 +++++ 8 files changed, 80 insertions(+), 25 deletions(-) diff --git a/app/controllers/maps_controller.rb b/app/controllers/maps_controller.rb index c20ce01fc..4c37ecf39 100644 --- a/app/controllers/maps_controller.rb +++ b/app/controllers/maps_controller.rb @@ -141,9 +141,9 @@ 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 = @user.upload_garmin_course(feature) + result, course_id = @user.upload_garmin_course(feature) Yabeda.feature_exports.increment(format: "garmin") - render json: { result:, course_id: @user.garmin_course_ids[feature.id.to_s] } + 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 diff --git a/app/javascript/controllers/feature/modal_controller.js b/app/javascript/controllers/feature/modal_controller.js index 306a6a5dc..69db184ef 100644 --- a/app/javascript/controllers/feature/modal_controller.js +++ b/app/javascript/controllers/feature/modal_controller.js @@ -435,14 +435,21 @@ export default class extends Controller { 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 url = 'https://connect.garmin.com/modern/course/' + encodeURIComponent(courseId) - status(courseId ? `${text}` : text, 'info', 'medium', 15000) + 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 { dom.hideElements('#preloader') } diff --git a/app/javascript/helpers/status.js b/app/javascript/helpers/status.js index 1bd621f32..c8956c768 100644 --- a/app/javascript/helpers/status.js +++ b/app/javascript/helpers/status.js @@ -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 => { diff --git a/app/javascript/maplibre/feature/details.js b/app/javascript/maplibre/feature/details.js index 46652ae10..3d71f900d 100644 --- a/app/javascript/maplibre/feature/details.js +++ b/app/javascript/maplibre/feature/details.js @@ -128,9 +128,10 @@ 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') }) - f.e('#feature-export-garmin a', e => { - e.dataset.url = e.dataset.url.replace(/feature\/[^/]*/, 'feature/' + feature.id) + 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) }) } diff --git a/app/models/concerns/garmin_account.rb b/app/models/concerns/garmin_account.rb index 85a6fc575..c260f2de3 100644 --- a/app/models/concerns/garmin_account.rb +++ b/app/models/concerns/garmin_account.rb @@ -9,15 +9,19 @@ module GarminAccount field :garmin_course_ids, type: Hash, default: {} end - # Returns :updated or :created. A course deleted in Garmin Connect answers 404 and gets created again. + # Returns [:updated or :created, courseId]. A course deleted in Garmin Connect answers 404 and gets created again. def upload_garmin_course(feature) - token = garmin_access_token - course = feature.to_garmin_course - course_id = garmin_course_ids[feature.id.to_s] - return :updated if course_id && update_garmin_course(token, course_id, course) - created = token.post(COURSE_PATH, course_request(course)).parsed - update!(garmin_course_ids: garmin_course_ids.merge(feature.id.to_s => created["courseId"])) - :created + 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 @@ -36,6 +40,25 @@ def save_garmin_token!(token) 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 + redis = Redis.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/1")) + key = "garmin_upload:#{id}" + owner = SecureRandom.hex + 50.times do + next sleep(0.2) unless redis.set(key, owner, nx: true, ex: 60) + begin + return yield + ensure + redis.del(key) if redis.get(key) == owner + end + end + raise "Another Garmin Connect upload of this user is still running" + ensure + redis&.close + 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" } } diff --git a/app/models/feature.rb b/app/models/feature.rb index 533a7f602..3ba53df55 100644 --- a/app/models/feature.rb +++ b/app/models/feature.rb @@ -56,12 +56,15 @@ def to_garmin_course coords = geometry["coordinates"] points = [ garmin_point(coords.first) ] distance = gain = loss = 0.0 - vertexes = coords.map { |c| Mapforge::LineIndex::FACTORY.point(c[0], c[1]) } - coords.zip(vertexes).each_cons(2) do |(a, va), (b, vb)| - segment = va.distance(vb) + 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| - points << garmin_point(a.zip(b).map { |x, y| x && y && x + (y - x) * i.fdiv(steps) }) + 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 diff --git a/spec/models/feature_spec.rb b/spec/models/feature_spec.rb index 09491bebc..7fe0b0354 100644 --- a/spec/models/feature_spec.rb +++ b/spec/models/feature_spec.rb @@ -26,13 +26,24 @@ expect(course[:geoPoints].last).to include(latitude: be_within(1e-9).of(49.435), elevation: be_within(1e-9).of(290)) end - it "keeps points at most 100m apart" do - factory = RGeo::Geographic.spherical_factory - gaps = course[:geoPoints].each_cons(2).map do |a, b| + def gaps(course) + factory = Mapforge::LineIndex::FACTORY + course[:geoPoints].each_cons(2).map do |a, b| factory.point(a[:longitude], a[:latitude]).distance(factory.point(b[:longitude], b[:latitude])) end - expect(gaps.max).to be <= 100 - expect(gaps.sum).to be_within(1).of(course[:distance]) + end + + it "keeps points at most 100m apart" do + expect(gaps(course).max).to be <= 100 + expect(gaps(course).sum).to be_within(1).of(course[:distance]) + end + + it "takes the short way across the antimeridian" do + feature.geometry["coordinates"] = [ [ 179.999, 0 ], [ -179.999, 0 ] ] + expect(gaps(course).max).to be <= 100 + expect(gaps(course).sum).to be_within(1).of(course[:distance]) + expect(course[:geoPoints].map { |p| p[:longitude] }).to all(be_between(-180, 180)) + expect(course[:geoPoints].last[:longitude]).to be_within(1e-9).of(-179.999) end it "uses a cycling course for bike routes" do diff --git a/spec/requests/maps_controller_spec.rb b/spec/requests/maps_controller_spec.rb index fda4c7513..870ebf051 100644 --- a/spec/requests/maps_controller_spec.rb +++ b/spec/requests/maps_controller_spec.rb @@ -93,6 +93,15 @@ def garmin_error(status, body = "") expect(user.reload.garmin_course_ids).to eq(feature.id.to_s => 43) end + it "keeps a mapping that another request saved during the upload" do + allow_any_instance_of(OAuth2::Client).to receive(:request) do + User.find(user.id).set("garmin_course_ids.other" => 7) + created + end + post path + expect(user.reload.garmin_course_ids).to eq("other" => 7, feature.id.to_s => 43) + end + it "updates a course that was sent before" do user.update!(garmin_course_ids: { feature.id.to_s => 42 }) expect_any_instance_of(OAuth2::Client).to receive(:request).once From 19f1b2a181da898c799259c799133be4305ff4f4 Mon Sep 17 00:00:00 2001 From: Thomas Schmidt Date: Sun, 15 Nov 2026 23:30:39 +0100 Subject: [PATCH 3/6] fix garmin lock --- app/models/concerns/garmin_account.rb | 11 +++++------ spec/requests/maps_controller_spec.rb | 8 ++++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/app/models/concerns/garmin_account.rb b/app/models/concerns/garmin_account.rb index c260f2de3..d68bbe90d 100644 --- a/app/models/concerns/garmin_account.rb +++ b/app/models/concerns/garmin_account.rb @@ -7,6 +7,7 @@ module GarminAccount 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. @@ -43,20 +44,18 @@ def save_garmin_token!(token) # 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 - redis = Redis.new(url: ENV.fetch("REDIS_URL", "redis://localhost:6379/1")) - key = "garmin_upload:#{id}" owner = SecureRandom.hex 50.times do - next sleep(0.2) unless redis.set(key, owner, nx: true, ex: 60) + 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 - redis.del(key) if redis.get(key) == owner + 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" - ensure - redis&.close end # A new hash per request: OAuth2::AccessToken merges the user's bearer token into these headers diff --git a/spec/requests/maps_controller_spec.rb b/spec/requests/maps_controller_spec.rb index 870ebf051..dfcfd5a99 100644 --- a/spec/requests/maps_controller_spec.rb +++ b/spec/requests/maps_controller_spec.rb @@ -102,6 +102,14 @@ def garmin_error(status, body = "") expect(user.reload.garmin_course_ids).to eq("other" => 7, feature.id.to_s => 43) end + it "takes over an expired upload lock and releases it" do + user.update!(garmin_lock: { "owner" => "crashed", "until" => 1.minute.ago }) + allow_any_instance_of(OAuth2::Client).to receive(:request).and_return(created) + post path + expect(response.parsed_body).to eq("result" => "created", "course_id" => 43) + expect(user.reload.garmin_lock).to be_nil + end + it "updates a course that was sent before" do user.update!(garmin_course_ids: { feature.id.to_s => 42 }) expect_any_instance_of(OAuth2::Client).to receive(:request).once From 1cd04804efec677c86098f8c4e365bffa3daff88 Mon Sep 17 00:00:00 2001 From: Thomas Schmidt Date: Mon, 16 Nov 2026 00:01:40 +0100 Subject: [PATCH 4/6] allow to upload .umap --- spec/features/map_use_cases_spec.rb | 2 +- spec/requests/maps_controller_spec.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spec/features/map_use_cases_spec.rb b/spec/features/map_use_cases_spec.rb index a6800b5a8..93a647122 100644 --- a/spec/features/map_use_cases_spec.rb +++ b/spec/features/map_use_cases_spec.rb @@ -23,7 +23,7 @@ it "copies the accept value of the import tile to the file picker" do click_button "Import data (gpx, kml)" expect(page.evaluate_script("document.querySelector('#fileInput').accept")) - .to eq ".gpx,.kml,.kmz,.geojson,.json" + .to eq ".gpx,.kml,.kmz,.geojson,.json,.umap" end it "starts the bike route mode" do diff --git a/spec/requests/maps_controller_spec.rb b/spec/requests/maps_controller_spec.rb index dfcfd5a99..5a756f0f0 100644 --- a/spec/requests/maps_controller_spec.rb +++ b/spec/requests/maps_controller_spec.rb @@ -228,7 +228,7 @@ def import_tile it "offers the import without images to a visitor" do get map.private_map_path - expect(import_tile["data-accept"]).to eq(".gpx,.kml,.kmz,.geojson,.json") + expect(import_tile["data-accept"]).to eq(".gpx,.kml,.kmz,.geojson,.json,.umap") expect(import_tile.text).to include("Import data (gpx, kml)") expect(response.body).to include("Please log in to upload images") end @@ -237,7 +237,7 @@ def import_tile user = create(:user) sign_in(user) get map.private_map_path - expect(import_tile["data-accept"]).to eq(".gpx,.kml,.kmz,.geojson,.json,image/*") + expect(import_tile["data-accept"]).to eq(".gpx,.kml,.kmz,.geojson,.json,.umap,image/*") expect(import_tile.text).to include("Import data (gpx, kml, image)") expect(response.body).not_to include("Please log in to upload images") end From ee262b5d69aae3733a2800999d728c032e33a8a3 Mon Sep 17 00:00:00 2001 From: Thomas Schmidt Date: Mon, 16 Nov 2026 00:04:44 +0100 Subject: [PATCH 5/6] fix map name and description --- app/models/feature.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/app/models/feature.rb b/app/models/feature.rb index 3ba53df55..c684d4b57 100644 --- a/app/models/feature.rb +++ b/app/models/feature.rb @@ -70,7 +70,8 @@ def to_garmin_course climb = a[2] && b[2] ? b[2] - a[2] : 0 climb.positive? ? gain += climb : loss -= climb end - { courseName: properties["title"].presence || "Mapforge track", description: properties["desc"].presence, + { 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 From e5f66bd7cc1f24fa8ee553adec6870ae0af0b14e Mon Sep 17 00:00:00 2001 From: Thomas Schmidt Date: Mon, 16 Nov 2026 00:18:59 +0100 Subject: [PATCH 6/6] garmin tests --- spec/requests/maps_controller_spec.rb | 17 ++++++++++++++ spec/requests/sessions_controller_spec.rb | 28 +++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/spec/requests/maps_controller_spec.rb b/spec/requests/maps_controller_spec.rb index 5a756f0f0..55e2a9bad 100644 --- a/spec/requests/maps_controller_spec.rb +++ b/spec/requests/maps_controller_spec.rb @@ -110,6 +110,23 @@ def garmin_error(status, body = "") expect(user.reload.garmin_lock).to be_nil end + it "refreshes an expired token and saves the new one" do + user.update!(garmin_token: { "access_token" => "old", "refresh_token" => "r", "expires_at" => 1.hour.ago.to_i }) + fresh = OAuth2::AccessToken.new(OAuth2::Client.new("id", "secret"), "new", refresh_token: "r2", + expires_at: 1.hour.from_now.to_i) + allow_any_instance_of(OAuth2::AccessToken).to receive(:refresh).and_return(fresh) + allow_any_instance_of(OAuth2::AccessToken).to receive(:post).and_return(created) + post path + expect(response.parsed_body).to eq("result" => "created", "course_id" => 43) + expect(user.reload.garmin_token).to include("access_token" => "new", "refresh_token" => "r2") + end + + it "gives up while another upload of the user holds the lock" do + user.update!(garmin_lock: { "owner" => "other", "until" => 1.minute.from_now }) + allow_any_instance_of(User).to receive(:sleep) + expect { post path }.to raise_error(RuntimeError, /still running/) + end + it "updates a course that was sent before" do user.update!(garmin_course_ids: { feature.id.to_s => 42 }) expect_any_instance_of(OAuth2::Client).to receive(:request).once diff --git a/spec/requests/sessions_controller_spec.rb b/spec/requests/sessions_controller_spec.rb index 9231b0409..1507a3dc2 100644 --- a/spec/requests/sessions_controller_spec.rb +++ b/spec/requests/sessions_controller_spec.rb @@ -57,6 +57,34 @@ def developer_login(name: "Test User", email: "test@mapforge.org") end end + describe "#create (garmin)" do + around do |example| + OmniAuth.config.test_mode = true + OmniAuth.config.mock_auth[:garmin] = OmniAuth::AuthHash.new( + provider: "garmin", uid: "g1", + credentials: { token: "abc", refresh_token: "def", expires_at: 1_900_000_000 }) + example.run + ensure + OmniAuth.config.mock_auth.delete(:garmin) + OmniAuth.config.test_mode = false + end + + it "links the Garmin account to the logged in user" do + user = create(:user) + sign_in(user) + get "/auth/garmin/callback" + expect(response).to redirect_to(my_path) + expect(user.reload.garmin_token).to eq("access_token" => "abc", "refresh_token" => "def", + "expires_at" => 1_900_000_000) + end + + it "sends a visitor without login to the login page" do + get "/auth/garmin/callback" + expect(response).to redirect_to(login_path) + expect(User.count).to eq 0 + end + end + describe "#logout" do it "destroys the session" do get "/auth/developer/callback", params: { name: "Test User", email: "test@mapforge.org" }