157 lines
4.6 KiB
Dart
157 lines
4.6 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../../../core/storage/secure_session_storage.dart';
|
|
import '../../../domain/repositories/auth_repository.dart';
|
|
import '../../../domain/repositories/settings_repository.dart';
|
|
import 'odoo_api_uri_builder.dart';
|
|
|
|
class OdooSessionApiClient {
|
|
OdooSessionApiClient({
|
|
required AuthRepository authRepository,
|
|
required SettingsRepository settingsRepository,
|
|
required SecureSessionStorage sessionStorage,
|
|
http.Client? client,
|
|
}) : _authRepository = authRepository,
|
|
_settingsRepository = settingsRepository,
|
|
_sessionStorage = sessionStorage,
|
|
_client = client ?? http.Client();
|
|
|
|
static const _timeout = Duration(seconds: 60);
|
|
final AuthRepository _authRepository;
|
|
final SettingsRepository _settingsRepository;
|
|
final SecureSessionStorage _sessionStorage;
|
|
final http.Client _client;
|
|
|
|
Future<Map<String, dynamic>> getJson(
|
|
String endpoint, {
|
|
Map<String, String> query = const {},
|
|
}) =>
|
|
_request('GET', endpoint, query: query);
|
|
|
|
Future<Map<String, dynamic>> postForm(
|
|
String endpoint, {
|
|
required Map<String, String> body,
|
|
Duration? timeout,
|
|
}) =>
|
|
_request('POST', endpoint, body: body, requestTimeout: timeout);
|
|
|
|
Future<Map<String, dynamic>> _request(
|
|
String method,
|
|
String endpoint, {
|
|
Map<String, String> query = const {},
|
|
Map<String, String> body = const {},
|
|
Duration? requestTimeout,
|
|
}) async {
|
|
if (!_authRepository.isAuthenticated ||
|
|
_authRepository.currentSession == null) {
|
|
throw const OdooApiException(
|
|
'session_required',
|
|
'A sessão expirou. Entre novamente.',
|
|
);
|
|
}
|
|
|
|
final settings = await _settingsRepository.load();
|
|
if (settings?.isConfigured != true) {
|
|
throw const OdooApiException(
|
|
'configuration_required',
|
|
'Configure o servidor antes de continuar.',
|
|
);
|
|
}
|
|
|
|
final cookie = await _sessionStorage.readCookie();
|
|
final sessionId = await _sessionStorage.readSessionId();
|
|
if (cookie == null || sessionId == null) {
|
|
throw const OdooApiException(
|
|
'session_required',
|
|
'A sessão do servidor não está disponível. Entre novamente.',
|
|
);
|
|
}
|
|
|
|
final endpointUri = OdooApiUriBuilder.endpoint(
|
|
Uri.parse(settings!.serverUrl),
|
|
endpoint,
|
|
);
|
|
final uri = method == 'GET'
|
|
? endpointUri.replace(
|
|
queryParameters: {'session_id': sessionId, ...query},
|
|
)
|
|
: endpointUri;
|
|
final request = http.Request(method, uri)
|
|
..followRedirects = false
|
|
..headers['Accept'] = 'application/json'
|
|
..headers['Cookie'] = cookie;
|
|
if (method == 'POST') {
|
|
request
|
|
..headers['Content-Type'] =
|
|
'application/x-www-form-urlencoded; charset=utf-8'
|
|
..body = Uri(queryParameters: {'session_id': sessionId, ...body}).query;
|
|
}
|
|
|
|
try {
|
|
final response = await _client
|
|
.send(request)
|
|
.then(http.Response.fromStream)
|
|
.timeout(requestTimeout ?? _timeout);
|
|
if (response.statusCode != HttpStatus.ok) {
|
|
throw OdooApiException(
|
|
'http_error',
|
|
'O servidor respondeu com erro HTTP ${response.statusCode}.',
|
|
);
|
|
}
|
|
|
|
final decoded = jsonDecode(response.body);
|
|
if (decoded is! Map<String, dynamic>) {
|
|
throw const OdooApiException(
|
|
'invalid_response',
|
|
'O servidor retornou uma resposta inválida.',
|
|
);
|
|
}
|
|
if (decoded['status'] != 'ok') {
|
|
final code = decoded['code'];
|
|
final message = decoded['message'];
|
|
throw OdooApiException(
|
|
code is String ? code : 'api_error',
|
|
message is String ? message : 'O servidor não concluiu a operação.',
|
|
);
|
|
}
|
|
return decoded;
|
|
} on TimeoutException {
|
|
throw const OdooApiException(
|
|
'timeout',
|
|
'Tempo esgotado ao consultar o servidor.',
|
|
);
|
|
} on SocketException {
|
|
throw const OdooApiException(
|
|
'network_error',
|
|
'Não foi possível alcançar o servidor.',
|
|
);
|
|
} on OdooApiException {
|
|
rethrow;
|
|
} on FormatException {
|
|
throw const OdooApiException(
|
|
'invalid_response',
|
|
'O servidor retornou dados inválidos.',
|
|
);
|
|
} catch (_) {
|
|
throw const OdooApiException(
|
|
'network_error',
|
|
'Falha de comunicação com o servidor.',
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
class OdooApiException implements Exception {
|
|
const OdooApiException(this.code, this.message);
|
|
|
|
final String code;
|
|
final String message;
|
|
|
|
@override
|
|
String toString() => message;
|
|
}
|