/* * This file is part of wger Workout Manager . * Copyright (c) 2020, wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; import 'package:wger/helpers/shared_preferences.dart'; import '../helpers/consts.dart'; class ApiClient { late final uri = Uri.parse('$serverUrl/api/v2/upload-powersync-data'); final String serverUrl; final http.Client _client; String token = ''; ApiClient(this.serverUrl, {http.Client? client}) : _client = client ?? http.Client(); Map getHeaders() { return { HttpHeaders.contentTypeHeader: 'application/json', HttpHeaders.authorizationHeader: 'Token $token', }; } /// Returns a powersync JWT token token /// /// Note that at the moment we use the permanent API token for authentication /// but this should be probably changed to the wger API JWT tokens in the /// future since they are not permanent and could be easily revoked. Future> getPowersyncToken() async { final prefs = PreferenceHelper.asyncPref; final apiData = json.decode((await prefs.getString(PREFS_USER))!); // _logger.info('posting our token "${apiData["token"]}" to $baseUrl/api/v2/powersync-token'); token = apiData['token']; final response = await _client.get( Uri.parse('$serverUrl/api/v2/powersync-token'), headers: { HttpHeaders.contentTypeHeader: 'application/json', HttpHeaders.authorizationHeader: 'Token ${apiData["token"]}', }, ); if (response.statusCode == 200) { return json.decode(response.body); } throw Exception('Failed to fetch token'); } // The methods below return the raw [http.Response] so the connector // can inspect the status code and the JSON body. The backend always // answers 200 (PowerSync-recommended pattern: non-2xx triggers an // infinite retry loop on the SDK side, which is wrong for permanent // rejections like validation failures), but encodes any rejection // as `{'error': '...', 'details': ...}` in the body. Future upsert(Map record) { return _client.put(uri, headers: getHeaders(), body: json.encode(record)); } Future update(Map record) { return _client.patch(uri, headers: getHeaders(), body: json.encode(record)); } Future delete(Map record) { return _client.delete(uri, headers: getHeaders(), body: json.encode(record)); } }