import 'dart:async'; import 'dart:convert'; import 'dart:developer'; import 'package:marianum_mobile/api/webuntis/webuntisApi.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'authenticateParams.dart'; import 'authenticateResponse.dart'; class Authenticate extends WebuntisApi { AuthenticateParams param; Authenticate(this.param) : super("authenticate", param, authenticatedResponse: false); @override Future run() async { awaitingResponse = true; String rawAnswer = await query(this); AuthenticateResponse response = finalize(AuthenticateResponse.fromJson(jsonDecode(rawAnswer)['result'])); _lastResponse = response; if(!awaitedResponse.isCompleted) awaitedResponse.complete(); return response; } static bool awaitingResponse = false; static Completer awaitedResponse = Completer(); static AuthenticateResponse? _lastResponse; static Future createSession() async { SharedPreferences preferences = await SharedPreferences.getInstance(); _lastResponse = await Authenticate( AuthenticateParams( user: preferences.getString("username")!, password: preferences.getString("password")!, ) ).run(); } static Future getSession() async { if(awaitingResponse) { log("Other query in progress... waiting"); await awaitedResponse.future; } if(_lastResponse == null) { log("Not authenticated... requesting"); awaitingResponse = true; await createSession(); } return _lastResponse!; } }