• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

wger-project / flutter / 30854254088

03 Aug 2026 09:21PM UTC coverage: 40.895% (-15.0%) from 55.93%
30854254088

Pull #1260

github

web-flow
Merge d93794de5 into e3affdd4f
Pull Request #1260: WIP: health sync

9980 of 24404 relevant lines covered (40.89%)

1.72 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

33.87
/lib/core/network/base_provider.dart
1
/*
2
 * This file is part of wger Workout Manager <https://github.com/wger-project>.
3
 * Copyright (c) 2020 - 2026 wger Team
4
 *
5
 * wger Workout Manager is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Affero General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU Affero General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU Affero General Public License
16
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18

19
import 'dart:async';
20
import 'dart:convert';
21
import 'dart:io';
22
import 'dart:math' as math;
23

24
import 'package:http/http.dart' as http;
25
import 'package:logging/logging.dart';
26
import 'package:package_info_plus/package_info_plus.dart';
27
import 'package:wger/core/exceptions/http_exception.dart';
28
import 'package:wger/core/helpers.dart';
29
import 'package:wger/core/network/auth_notifier.dart' show getAppNameHeader;
30

31
/// default timeout for GET requests
32
const DEFAULT_TIMEOUT = Duration(seconds: 15);
33

34
/// Base provider class.
35
///
36
/// Provides a couple of comfort functions so we avoid a bit of boilerplate.
37
/// Holds the [serverUrl] + app version snapshot and a [client] that already
38
/// handles authentication for every outgoing request (see `AuthHttpClient`).
39
/// Building the `Authorization` header is therefore *not* a responsibility
40
/// of this class anymore, the client owns it.
41
class WgerBaseProvider {
42
  final _logger = Logger('WgerBaseProvider');
43

44
  final String? serverUrl;
45
  final PackageInfo? applicationVersion;
46
  late http.Client client;
47

48
  WgerBaseProvider({this.serverUrl, this.applicationVersion, http.Client? client}) {
7✔
49
    this.client = client ?? http.Client();
8✔
50
  }
51

52
  String getAppNameHeaderValue() => getAppNameHeader(applicationVersion);
15✔
53

54
  /// Default non-auth headers for outgoing requests. The `Authorization`
55
  /// header is injected by the underlying `AuthHttpClient`
56
  Map<String, String> getDefaultHeaders({String? language}) {
1✔
57
    final out = {
1✔
58
      HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8',
59
      HttpHeaders.userAgentHeader: getAppNameHeaderValue(),
1✔
60
    };
61

62
    if (language != null) {
63
      out[HttpHeaders.acceptLanguageHeader] = language;
×
64
    }
65

66
    return out;
67
  }
68

69
  /// Helper function to make a URL.
70
  Uri makeUrl(String path, {int? id, String? objectMethod, Map<String, dynamic>? query}) {
2✔
71
    return makeUri(serverUrl!, path, id: id, objectMethod: objectMethod, query: query);
4✔
72
  }
73

74
  /// Builds a `/allauth/app/v1/<path>` URL for the headless API.
75
  Uri makeHeadlessUrl(String path) => makeHeadlessUri(serverUrl!, path);
×
76

77
  /// Fetch and retrieve the overview list of objects, returns the JSON parsed response
78
  /// with a simple retry mechanism for transient errors.
79
  Future<dynamic> fetch(
×
80
    Uri uri, {
81
    int maxRetries = 3,
82
    Duration initialDelay = const Duration(milliseconds: 250),
83
    Duration timeout = DEFAULT_TIMEOUT,
84
    String? language,
85
  }) async {
86
    int attempt = 0;
87
    final random = math.Random();
×
88

89
    Future<void> wait(String reason) async {
×
90
      final backoff = (initialDelay.inMilliseconds * math.pow(2, attempt - 1)).toInt();
×
91
      final jitter = random.nextInt((backoff * 0.25).toInt() + 1); // up to 25% jitter
×
92
      final delay = backoff + jitter;
×
93
      _logger.info('Retrying fetch for $uri, attempt $attempt (${delay}ms), reason: $reason');
×
94

95
      await Future.delayed(Duration(milliseconds: delay));
×
96
    }
97

98
    while (true) {
99
      try {
100
        final response = await client
×
101
            .get(uri, headers: getDefaultHeaders(language: language))
×
102
            .timeout(timeout);
×
103

104
        if (response.statusCode >= 400) {
×
105
          // Retry on server errors (5xx); e.g. 502 might be transient
106
          if (response.statusCode >= 500 && attempt < maxRetries) {
×
107
            attempt++;
×
108
            await wait('status code ${response.statusCode}');
×
109
            continue;
110
          }
111
          throw WgerHttpException(response);
×
112
        }
113

114
        return json.decode(utf8.decode(response.bodyBytes)) as dynamic;
×
115
      } catch (e) {
116
        final isRetryable =
117
            e is SocketException || e is http.ClientException || e is TimeoutException;
×
118
        if (isRetryable && attempt < maxRetries) {
×
119
          attempt++;
×
120
          await wait(e.toString());
×
121
          continue;
122
        }
123

124
        rethrow;
125
      }
126
    }
127
  }
128

129
  /// Fetch and retrieve the overview list of objects, returns the JSON parsed response
130
  Future<List<dynamic>> fetchPaginated(
×
131
    Uri uri, {
132
    String? language,
133
    Duration timeout = DEFAULT_TIMEOUT,
134
  }) async {
135
    final out = [];
×
136
    var url = uri;
137
    var allPagesProcessed = false;
138

139
    while (!allPagesProcessed) {
140
      final data = await fetch(url, language: language, timeout: timeout);
×
141

142
      data['results'].forEach((e) => out.add(e));
×
143

144
      if (data['next'] == null) {
×
145
        allPagesProcessed = true;
146
      } else {
147
        url = Uri.parse(data['next']);
×
148
      }
149
    }
150

151
    return out;
152
  }
153

154
  /// POSTs a new object
155
  Future<Map<String, dynamic>> post(Map<String, dynamic> data, Uri uri) async {
×
156
    final response = await client.post(
×
157
      uri,
158
      headers: getDefaultHeaders(),
×
159
      body: json.encode(data),
×
160
    );
161

162
    // Something wrong with our request
163
    if (response.statusCode >= 400) {
×
164
      throw WgerHttpException(response);
×
165
    }
166

167
    return json.decode(response.body);
×
168
  }
169

170
  /// PUTs to the given URI.
171
  Future<Map<String, dynamic>> put(Map<String, dynamic> data, Uri uri) async {
×
172
    final response = await client.put(uri, headers: getDefaultHeaders(), body: json.encode(data));
×
173

174
    if (response.statusCode >= 400) {
×
175
      throw WgerHttpException(response);
×
176
    }
177

178
    return response.body.isEmpty ? {} : json.decode(response.body);
×
179
  }
180

181
  /// PATCHEs an existing object
182
  Future<Map<String, dynamic>> patch(Map<String, dynamic> data, Uri uri) async {
1✔
183
    final response = await client.patch(
2✔
184
      uri,
185
      headers: getDefaultHeaders(),
1✔
186
      body: json.encode(data),
1✔
187
    );
188

189
    // Something wrong with our request
190
    if (response.statusCode >= 400) {
2✔
191
      throw WgerHttpException(response);
1✔
192
    }
193

194
    return json.decode(response.body);
2✔
195
  }
196

197
  /// DELETEs an existing object
198
  Future<http.Response> deleteRequest(String url, int id) async {
1✔
199
    final deleteUrl = makeUrl(url, id: id);
1✔
200

201
    final response = await client.delete(
2✔
202
      deleteUrl,
203
      headers: getDefaultHeaders(),
1✔
204
    );
205

206
    // Something wrong with our request
207
    if (response.statusCode >= 400) {
2✔
208
      throw WgerHttpException(response);
1✔
209
    }
210
    return response;
211
  }
212
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc