Files
Client/lib/api/webuntis/queries/authenticate/authenticate.dart
T
2026-05-05 13:49:45 +02:00

62 lines
1.8 KiB
Dart

import 'dart:async';
import 'dart:convert';
import '../../../../model/accountData.dart';
import '../../webuntisApi.dart';
import 'authenticateParams.dart';
import 'authenticateResponse.dart';
class Authenticate extends WebuntisApi {
AuthenticateParams param;
Authenticate(this.param) : super('authenticate', param, authenticatedResponse: false);
@override
Future<AuthenticateResponse> run() async {
awaitingResponse = true;
try {
var rawAnswer = await query(this);
AuthenticateResponse response = finalize(AuthenticateResponse.fromJson(jsonDecode(rawAnswer)['result']));
_lastResponse = response;
if(!awaitedResponse.isCompleted) awaitedResponse.complete();
return response;
} catch (e) {
// Surface the error to anyone waiting on the current completer, then
// install a fresh one so a future attempt can succeed. Without this,
// any later call to getSession() would hang forever on a completer
// that is already settled with no listeners (or never settles at all).
if(!awaitedResponse.isCompleted) awaitedResponse.completeError(e);
awaitedResponse = Completer();
rethrow;
} finally {
awaitingResponse = false;
}
}
static bool awaitingResponse = false;
static Completer awaitedResponse = Completer();
static AuthenticateResponse? _lastResponse;
static Future<void> createSession() async {
_lastResponse = await Authenticate(
AuthenticateParams(
user: AccountData().getUsername(),
password: AccountData().getPassword(),
)
).run();
}
static Future<AuthenticateResponse> getSession() async {
if(awaitingResponse) {
await awaitedResponse.future;
}
if(_lastResponse == null) {
awaitingResponse = true;
await createSession();
}
return _lastResponse!;
}
}