BotZ_app/lib/connection.dart

85 lines
2.3 KiB
Dart

import 'package:http/http.dart';
import 'package:logger/logger.dart';
import 'dart:convert';
final log = Logger();
class Connection {
// Connection constructor.
Connection(this.username, this.password, this.baseAddress);
// baseAddress contains the base address to the BotZ server
// assuming that the APIs are located at /api/.
final String baseAddress;
// Username is the username to autenticate against the foreign
// service.
final String username;
// Password is the password to autenticate against the foreign
// service.
final String password;
// _stateCookie is private. It contains the HTTP state cookie
// assigned by the server.
String _stateCookie = "";
bool _loggedIn = false;
void login() async {
// TODO: perform the login and obtain the cookie. Set the
// _loggedIn state accordingly.
}
void logout() async {
// TODO: perform the logout. If successful, empty the _stateCookie
// and set the _loggedIn state accordingly.
}
void checkin() async {
// TODO: perform the checkin if possible.
}
void checkout() async {
// TODO: perform the checkout if possible.
}
Future<Map<String, dynamic>> getMovements() async {
// TODO: query /api/movements and retrieve the list of movements.
return {};
}
}
class UnauthorizedException implements ClientException {
UnauthorizedException(this.uri);
final String message = "Unauthorized";
final Uri uri;
}
Response handleResponse(Response resp) {
final c = resp.statusCode;
if (c >= 200 && c < 400) {
} else if (c == 401) {
throw UnauthorizedException(resp.request.url);
} else if (c >=400 || c < 500) {
throw ClientException("Unexpected return code: $c", resp.request.url);
} else if (c >= 500) {
throw ClientException("Server error: $c", resp.request.url);
}
return resp;
}
class BotZContent {
BotZContent(this.response) {
this.response.then((resp) => handleResponse(resp))
.then((value) => this.initContent(value))
.catchError((err) => log.e(err));
}
final Future<Response> response;
Map<String, dynamic> body;
List<String> cookies;
void initContent(Response resp) {
this.cookies = resp.headers['cookies'].split(';');
this.body = jsonDecode(resp.body);
}
}