Files
swiftcontrol/lib/services/activity_sync/activity_sync_api.dart
Jonas Acker 1bdcc20219 Upload rides to Strava and intervals.icu; Garmin via its import page
Connect an account in Settings > Connected accounts (in the browser, through
bikecontrol.app/connect/<service>); rides upload by hand from Export or
automatically once saved. Tokens stay in the activity-sync function. Garmin
has no upload API for us and its app files a shared .fit as a course, so the
Garmin row saves the file and opens Connect's import page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:44:18 +01:00

211 lines
6.9 KiB
Dart

import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
/// The services a ride can be uploaded to through a connected account.
/// [id] is the wire name the `activity-sync` function uses.
enum ActivityService {
strava('strava', 'Strava'),
intervals('intervals', 'intervals.icu');
const ActivityService(this.id, this.displayName);
final String id;
final String displayName;
static ActivityService? fromId(Object? id) {
for (final s in values) {
if (s.id == id) return s;
}
return null;
}
}
class ActivityConnection {
const ActivityConnection({required this.service, this.athleteName, this.reauthRequired = false});
final ActivityService service;
final String? athleteName;
/// The service no longer accepts our token: the rider has to connect again.
final bool reauthRequired;
}
/// What the backend says: which services are set up there, and which of them
/// this rider connected.
class ActivityConnections {
const ActivityConnections({this.available = const {}, this.connections = const {}});
final Set<ActivityService> available;
final Map<ActivityService, ActivityConnection> connections;
ActivityConnection? operator [](ActivityService s) => connections[s];
bool isConnected(ActivityService s) => connections[s]?.reauthRequired == false;
static ActivityConnections fromJson(Map<String, Object?> json) {
final available = <ActivityService>{
for (final id in (json['available'] as List? ?? const []))
if (ActivityService.fromId(id) case final s?) s,
};
final connections = <ActivityService, ActivityConnection>{};
for (final raw in (json['connections'] as List? ?? const [])) {
if (raw is! Map) continue;
final service = ActivityService.fromId(raw['provider']);
if (service == null) continue;
connections[service] = ActivityConnection(
service: service,
athleteName: raw['athlete_name'] as String?,
reauthRequired: raw['reauth_required'] == true,
);
}
return ActivityConnections(available: available, connections: connections);
}
}
/// One answer to an upload (or to a poll of a Strava upload still processing).
class ActivityUploadResult {
const ActivityUploadResult({required this.state, this.uploadId, this.activityUrl, this.error});
/// `ready`, `processing`, `duplicate` or `failed`.
final String state;
final String? uploadId;
final String? activityUrl;
final String? error;
bool get isProcessing => state == 'processing';
static ActivityUploadResult fromJson(Map<String, Object?> json) => ActivityUploadResult(
state: json['state'] as String? ?? 'failed',
uploadId: json['upload_id'] as String?,
activityUrl: json['activity_url'] as String?,
error: json['error'] as String?,
);
}
/// Why a call to the function did not go through. [code] is the function's
/// `error` (`not_connected`, `reauth_required`, `rate_limited`, …), or
/// `network` when it was never reached.
class ActivitySyncException implements Exception {
const ActivitySyncException(this.code, {this.statusCode, this.message});
final String code;
final int? statusCode;
final String? message;
bool get needsReconnect => code == 'reauth_required' || code == 'not_connected';
@override
String toString() => 'ActivitySyncException($code, status: $statusCode${message == null ? '' : ', $message'})';
}
/// The `activity-sync` Supabase Edge Function over raw HTTP (the upload body
/// is the .fit itself, which `functions.invoke` cannot send). Every call
/// carries the rider's fresh session token.
class ActivitySyncApi {
ActivitySyncApi({
required this.baseUrl,
required this.anonKey,
required this.accessToken,
http.Client? client,
}) : _client = client;
/// `https://<project>.supabase.co/functions/v1/activity-sync`
final String baseUrl;
final String anonKey;
final Future<String> Function() accessToken;
http.Client? _client;
/// Created on first use: building the app (and its tests) opens no socket.
http.Client get _http => _client ??= http.Client();
Future<Map<String, String>> _headers({String? contentType}) async => {
'Authorization': 'Bearer ${await accessToken()}',
'apikey': anonKey,
'Content-Type': ?contentType,
};
Future<Map<String, Object?>> _send(Future<http.Response> Function() call) async {
final http.Response response;
try {
response = await call();
} catch (e) {
throw ActivitySyncException('network', message: e.toString());
}
Map<String, Object?> json = const {};
try {
final decoded = jsonDecode(response.body);
if (decoded is Map<String, Object?>) json = decoded;
} catch (_) {
// A non-JSON body (a gateway error page): the status code says enough.
}
if (response.statusCode < 200 || response.statusCode >= 300) {
throw ActivitySyncException(
json['error'] as String? ?? 'http_${response.statusCode}',
statusCode: response.statusCode,
message: json['message'] as String?,
);
}
return json;
}
Uri _uri(String route, [Map<String, String>? query]) =>
Uri.parse('$baseUrl/$route').replace(queryParameters: query == null || query.isEmpty ? null : query);
Future<ActivityConnections> connections() async => ActivityConnections.fromJson(
await _send(() async => _http.get(_uri('connections'), headers: await _headers())),
);
/// The provider's consent page for this rider.
Future<Uri> connectUrl(ActivityService service, {required String platform}) async {
final json = await _send(
() async => _http.post(
_uri('connect'),
headers: await _headers(contentType: 'application/json'),
body: jsonEncode({'provider': service.id, 'platform': platform}),
),
);
final url = json['authorize_url'];
if (url is! String) throw const ActivitySyncException('bad_response');
return Uri.parse(url);
}
Future<void> disconnect(ActivityService service) => _send(
() async => _http.post(
_uri('disconnect'),
headers: await _headers(contentType: 'application/json'),
body: jsonEncode({'provider': service.id}),
),
);
Future<ActivityUploadResult> upload(
ActivityService service,
Uint8List fit, {
required String rideId,
String? name,
}) async => ActivityUploadResult.fromJson(
await _send(
() async => _http.post(
_uri('upload', {
'provider': service.id,
'ride_id': rideId,
'name': ?name,
}),
headers: await _headers(contentType: 'application/octet-stream'),
body: fit,
),
),
);
Future<ActivityUploadResult> uploadStatus(ActivityService service, String uploadId) async =>
ActivityUploadResult.fromJson(
await _send(
() async => _http.get(
_uri('upload-status', {'provider': service.id, 'upload_id': uploadId}),
headers: await _headers(),
),
),
);
}