api.service.dart 3.6 KB

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