2019-04-22 17:16:26 +00:00
|
|
|
import 'dart:convert';
|
|
|
|
import 'dart:io';
|
|
|
|
|
2019-04-23 12:35:41 +00:00
|
|
|
import 'package:comunic/helpers/account_credentials_helper.dart';
|
2019-04-22 17:16:26 +00:00
|
|
|
import 'package:comunic/models/api_request.dart';
|
|
|
|
import 'package:comunic/models/api_response.dart';
|
|
|
|
import 'package:comunic/models/config.dart';
|
|
|
|
|
|
|
|
/// API Helper
|
|
|
|
///
|
|
|
|
/// @author Pierre HUBERT
|
|
|
|
|
|
|
|
class APIHelper {
|
|
|
|
final _httpClient = HttpClient();
|
|
|
|
|
|
|
|
/// Execute a [request] on the server and returns a [APIResponse]
|
|
|
|
///
|
|
|
|
/// This method should never throw but the response code of the [APIResponse]
|
|
|
|
/// should be verified before accessing response content
|
|
|
|
Future<APIResponse> exec(APIRequest request) async {
|
|
|
|
try {
|
|
|
|
//Add API tokens
|
|
|
|
request.addString("serviceName", config().serviceName);
|
|
|
|
request.addString("serviceToken", config().serviceToken);
|
|
|
|
|
|
|
|
//Add user tokens (if required)
|
2019-04-23 12:35:41 +00:00
|
|
|
if (request.needLogin) {
|
|
|
|
final tokens = await AccountCredentialsHelper().get();
|
|
|
|
assert(tokens != null);
|
|
|
|
request.addString("userToken1", tokens.tokenOne);
|
|
|
|
request.addString("userToken2", tokens.tokenTwo);
|
|
|
|
}
|
2019-04-22 17:16:26 +00:00
|
|
|
|
|
|
|
// Prepare request body
|
|
|
|
String requestBody = "";
|
|
|
|
request.args.forEach((key, value) => requestBody +=
|
|
|
|
Uri.encodeQueryComponent(key) +
|
|
|
|
"=" +
|
|
|
|
Uri.encodeQueryComponent(value) +
|
|
|
|
"&");
|
|
|
|
|
|
|
|
List<int> bodyBytes = utf8.encode(requestBody);
|
|
|
|
|
|
|
|
// Determine server URL
|
|
|
|
final path = config().apiServerUri + request.uri;
|
|
|
|
Uri url;
|
|
|
|
if (!config().apiServerSecure)
|
|
|
|
url = Uri.http(config().apiServerName, path);
|
|
|
|
else
|
|
|
|
url = Uri.https(config().apiServerName, path);
|
|
|
|
|
|
|
|
//Connect to server
|
|
|
|
final connection = await _httpClient.postUrl(url);
|
|
|
|
connection.headers.set("Content-Length", bodyBytes.length.toString());
|
|
|
|
connection.headers
|
|
|
|
.set("Content-Type", "application/x-www-form-urlencoded");
|
|
|
|
connection.add(bodyBytes);
|
|
|
|
|
|
|
|
final response = await connection.close();
|
|
|
|
|
|
|
|
if (response.statusCode != HttpStatus.ok)
|
|
|
|
return APIResponse(response.statusCode, null);
|
|
|
|
|
|
|
|
//Save & return response
|
|
|
|
final responseBody = await response.transform(utf8.decoder).join();
|
|
|
|
|
|
|
|
return APIResponse(response.statusCode, responseBody);
|
|
|
|
} on Exception catch (e) {
|
|
|
|
print(e.toString());
|
|
|
|
print("Could not execute a request!");
|
|
|
|
return APIResponse(-1, null);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|