Parses the JMAP Session object (RFC 8620 §2): fetches GET {jmapUrl},
extracts apiUrl and primary accountId, and wraps API calls via
call(methodCalls) which POSTs to apiUrl with Basic Auth.
Handles relative apiUrl, primaryAccounts fallback, and top-level
JMAP error responses. Covered by unit tests.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
135 lines
4.1 KiB
Dart
135 lines
4.1 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:http/http.dart' as http;
|
|
|
|
const _using = [
|
|
'urn:ietf:params:jmap:core',
|
|
'urn:ietf:params:jmap:mail',
|
|
];
|
|
|
|
/// A connected JMAP session. Fetch via [JmapClient.connect].
|
|
///
|
|
/// Parses the JMAP Session object (RFC 8620 §2), stores the resolved
|
|
/// [apiUrl] and server-side [accountId], and wraps API calls in [call].
|
|
class JmapClient {
|
|
JmapClient._({
|
|
required http.Client httpClient,
|
|
required String credentials,
|
|
required Uri apiUrl,
|
|
required String accountId,
|
|
}) : _httpClient = httpClient,
|
|
_credentials = credentials,
|
|
_apiUrl = apiUrl,
|
|
_accountId = accountId;
|
|
|
|
final http.Client _httpClient;
|
|
final String _credentials;
|
|
final Uri _apiUrl;
|
|
final String _accountId;
|
|
|
|
String get accountId => _accountId;
|
|
|
|
/// Fetches the JMAP Session object from [jmapUrl] and returns a connected
|
|
/// client. Throws [JmapException] on HTTP errors or missing capabilities.
|
|
static Future<JmapClient> connect({
|
|
required http.Client httpClient,
|
|
required Uri jmapUrl,
|
|
required String username,
|
|
required String password,
|
|
}) async {
|
|
final credentials = base64.encode(utf8.encode('$username:$password'));
|
|
final resp = await httpClient.get(
|
|
jmapUrl,
|
|
headers: {'Authorization': 'Basic $credentials'},
|
|
).timeout(const Duration(seconds: 10));
|
|
|
|
if (resp.statusCode == 401 || resp.statusCode == 403) {
|
|
throw JmapException('Authentication failed (HTTP ${resp.statusCode})');
|
|
}
|
|
if (resp.statusCode != 200) {
|
|
throw JmapException('Session fetch failed (HTTP ${resp.statusCode})');
|
|
}
|
|
|
|
final session = jsonDecode(resp.body) as Map<String, dynamic>;
|
|
final apiUrl = _extractApiUrl(session, jmapUrl);
|
|
final accountId = _extractAccountId(session);
|
|
|
|
return JmapClient._(
|
|
httpClient: httpClient,
|
|
credentials: credentials,
|
|
apiUrl: apiUrl,
|
|
accountId: accountId,
|
|
);
|
|
}
|
|
|
|
/// Issues a JMAP API request with [methodCalls].
|
|
///
|
|
/// Each call is a triple `[methodName, arguments, callId]`.
|
|
/// Returns the raw `methodResponses` list from the server.
|
|
///
|
|
/// Throws [JmapException] on HTTP errors or a top-level JMAP error response.
|
|
Future<List<dynamic>> call(List<List<dynamic>> methodCalls) async {
|
|
final body = jsonEncode({
|
|
'using': _using,
|
|
'methodCalls': methodCalls,
|
|
});
|
|
|
|
final resp = await _httpClient
|
|
.post(
|
|
_apiUrl,
|
|
headers: {
|
|
'Authorization': 'Basic $_credentials',
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: body,
|
|
)
|
|
.timeout(const Duration(seconds: 30));
|
|
|
|
if (resp.statusCode != 200) {
|
|
throw JmapException('API call failed (HTTP ${resp.statusCode})');
|
|
}
|
|
|
|
final decoded = jsonDecode(resp.body) as Map<String, dynamic>;
|
|
|
|
// Top-level error (e.g. unknownCapability)
|
|
if (decoded.containsKey('type')) {
|
|
throw JmapException(
|
|
'JMAP error: ${decoded['type']} — ${decoded['description'] ?? ''}');
|
|
}
|
|
|
|
return decoded['methodResponses'] as List<dynamic>;
|
|
}
|
|
|
|
static Uri _extractApiUrl(Map<String, dynamic> session, Uri sessionUri) {
|
|
final raw = session['apiUrl'] as String?;
|
|
if (raw == null || raw.isEmpty) {
|
|
throw JmapException('Session missing apiUrl');
|
|
}
|
|
// apiUrl may be relative (RFC 8620 §2 allows it)
|
|
return sessionUri.resolve(raw);
|
|
}
|
|
|
|
static String _extractAccountId(Map<String, dynamic> session) {
|
|
final primaryAccounts =
|
|
session['primaryAccounts'] as Map<String, dynamic>?;
|
|
final id = primaryAccounts?['urn:ietf:params:jmap:mail'] as String? ??
|
|
primaryAccounts?['urn:ietf:params:jmap:core'] as String?;
|
|
if (id != null) return id;
|
|
|
|
// Fall back to first account in the accounts map
|
|
final accounts = session['accounts'] as Map<String, dynamic>?;
|
|
if (accounts != null && accounts.isNotEmpty) {
|
|
return accounts.keys.first;
|
|
}
|
|
throw JmapException('Session has no usable accountId');
|
|
}
|
|
}
|
|
|
|
class JmapException implements Exception {
|
|
JmapException(this.message);
|
|
final String message;
|
|
|
|
@override
|
|
String toString() => 'JmapException: $message';
|
|
}
|