api.service.dart 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:flutter/material.dart';
  5. import 'package:immich_mobile/shared/models/store.dart';
  6. import 'package:immich_mobile/utils/url_helper.dart';
  7. import 'package:openapi/api.dart';
  8. import 'package:http/http.dart';
  9. class ApiService {
  10. late ApiClient _apiClient;
  11. late UserApi userApi;
  12. late AuthenticationApi authenticationApi;
  13. late OAuthApi oAuthApi;
  14. late AlbumApi albumApi;
  15. late AssetApi assetApi;
  16. late SearchApi searchApi;
  17. late ServerInfoApi serverInfoApi;
  18. late PartnerApi partnerApi;
  19. late PersonApi personApi;
  20. late AuditApi auditApi;
  21. ApiService() {
  22. final endpoint = Store.tryGet(StoreKey.serverEndpoint);
  23. if (endpoint != null && endpoint.isNotEmpty) {
  24. setEndpoint(endpoint);
  25. }
  26. }
  27. String? _authToken;
  28. setEndpoint(String endpoint) {
  29. _apiClient = ApiClient(basePath: endpoint);
  30. if (_authToken != null) {
  31. setAccessToken(_authToken!);
  32. }
  33. userApi = UserApi(_apiClient);
  34. authenticationApi = AuthenticationApi(_apiClient);
  35. oAuthApi = OAuthApi(_apiClient);
  36. albumApi = AlbumApi(_apiClient);
  37. assetApi = AssetApi(_apiClient);
  38. serverInfoApi = ServerInfoApi(_apiClient);
  39. searchApi = SearchApi(_apiClient);
  40. partnerApi = PartnerApi(_apiClient);
  41. personApi = PersonApi(_apiClient);
  42. auditApi = AuditApi(_apiClient);
  43. }
  44. Future<String> resolveAndSetEndpoint(String serverUrl) async {
  45. final endpoint = await _resolveEndpoint(serverUrl);
  46. setEndpoint(endpoint);
  47. // Save in hivebox for next startup
  48. Store.put(StoreKey.serverEndpoint, endpoint);
  49. return endpoint;
  50. }
  51. /// Takes a server URL and attempts to resolve the API endpoint.
  52. ///
  53. /// Input: [schema://]host[:port][/path]
  54. /// schema - optional (default: https)
  55. /// host - required
  56. /// port - optional (default: based on schema)
  57. /// path - optional
  58. Future<String> _resolveEndpoint(String serverUrl) async {
  59. final url = sanitizeUrl(serverUrl);
  60. if (!await _isEndpointAvailable(serverUrl)) {
  61. throw ApiException(503, "Server is not reachable");
  62. }
  63. // Check for /.well-known/immich
  64. final wellKnownEndpoint = await _getWellKnownEndpoint(url);
  65. if (wellKnownEndpoint.isNotEmpty) return wellKnownEndpoint;
  66. // Otherwise, assume the URL provided is the api endpoint
  67. return url;
  68. }
  69. Future<bool> _isEndpointAvailable(String serverUrl) async {
  70. final Client client = Client();
  71. if (!serverUrl.endsWith('/api')) {
  72. serverUrl += '/api';
  73. }
  74. // Throw Socket or Timeout exceptions,
  75. // we do not care if the endpoints hits an HTTP error
  76. try {
  77. await client
  78. .get(
  79. Uri.parse(serverUrl),
  80. )
  81. .timeout(const Duration(seconds: 5));
  82. } on TimeoutException catch (_) {
  83. return false;
  84. } on SocketException catch (_) {
  85. return false;
  86. }
  87. return true;
  88. }
  89. Future<String> _getWellKnownEndpoint(String baseUrl) async {
  90. final Client client = Client();
  91. try {
  92. final res = await client.get(
  93. Uri.parse("$baseUrl/.well-known/immich"),
  94. headers: {"Accept": "application/json"},
  95. );
  96. if (res.statusCode == 200) {
  97. final data = jsonDecode(res.body);
  98. final endpoint = data['api']['endpoint'].toString();
  99. if (endpoint.startsWith('/')) {
  100. // Full URL is relative to base
  101. return "$baseUrl$endpoint";
  102. }
  103. return endpoint;
  104. }
  105. } catch (e) {
  106. debugPrint("Could not locate /.well-known/immich at $baseUrl");
  107. }
  108. return "";
  109. }
  110. setAccessToken(String accessToken) {
  111. _authToken = accessToken;
  112. _apiClient.addDefaultHeader('Authorization', 'Bearer $accessToken');
  113. }
  114. ApiClient get apiClient => _apiClient;
  115. }