yay ASv2 removed

This commit is contained in:
ivan2282
2025-11-19 19:19:28 +03:00
parent 575c43ce63
commit 3388b78f8c
6 changed files with 340 additions and 1087 deletions

View File

@@ -5,11 +5,18 @@ import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/services.dart';
import 'package:gwid/connection/connection_logger.dart';
import 'package:gwid/connection/connection_state.dart' as conn_state;
import 'package:gwid/connection/health_monitor.dart';
import 'package:gwid/image_cache_service.dart';
import 'package:gwid/models/contact.dart';
import 'package:gwid/models/message.dart';
import 'package:gwid/models/profile.dart';
import 'package:gwid/proxy_service.dart';
import 'package:gwid/services/account_manager.dart';
import 'package:gwid/services/avatar_cache_service.dart';
import 'package:gwid/services/cache_service.dart';
import 'package:gwid/services/chat_cache_service.dart';
import 'package:gwid/spoofing_service.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
@@ -82,6 +89,18 @@ class ApiService {
minutes: 5,
);
final CacheService _cacheService = CacheService();
final AvatarCacheService _avatarCacheService = AvatarCacheService();
final ChatCacheService _chatCacheService = ChatCacheService();
bool _cacheServicesInitialized = false;
final ConnectionLogger _connectionLogger = ConnectionLogger();
final conn_state.ConnectionStateManager _connectionStateManager =
conn_state.ConnectionStateManager();
final HealthMonitor _healthMonitor = HealthMonitor();
String? _currentServerUrl;
bool _isLoadingBlockedContacts = false;
bool _isSessionReady = false;
@@ -95,6 +114,13 @@ class ApiService {
final _connectionLogController = StreamController<String>.broadcast();
Stream<String> get connectionLog => _connectionLogController.stream;
List<LogEntry> get logs => _connectionLogger.logs;
Stream<conn_state.ConnectionInfo> get connectionState =>
_connectionStateManager.stateStream;
Stream<HealthMetrics> get healthMetrics => _healthMonitor.metricsStream;
final List<String> _connectionLogCache = [];
List<String> get connectionLogCache => _connectionLogCache;
@@ -133,12 +159,23 @@ class ApiService {
Timer? _reconnectTimer;
bool _isReconnecting = false;
void _log(String message) {
void _log(
String message, {
LogLevel level = LogLevel.info,
String category = 'API',
Map<String, dynamic>? data,
}) {
print(message);
_connectionLogCache.add(message);
if (!_connectionLogController.isClosed) {
_connectionLogController.add(message);
}
_connectionLogger.log(
message,
level: level,
category: category,
data: data,
);
}
void _emitLocal(Map<String, dynamic> frame) {
@@ -204,6 +241,48 @@ class ApiService {
_isAppInForeground = isForeground;
}
void _updateConnectionState(
conn_state.ConnectionState state, {
String? message,
int? attemptNumber,
Duration? reconnectDelay,
int? latency,
Map<String, dynamic>? metadata,
}) {
_connectionStateManager.setState(
state,
message: message,
attemptNumber: attemptNumber,
reconnectDelay: reconnectDelay,
serverUrl: _currentServerUrl,
latency: latency,
metadata: metadata,
);
}
void _startHealthMonitoring() {
_healthMonitor.startMonitoring(serverUrl: _currentServerUrl);
}
void _stopHealthMonitoring() {
_healthMonitor.stopMonitoring();
}
Future<void> initialize() async {
await _ensureCacheServicesInitialized();
}
Future<void> _ensureCacheServicesInitialized() async {
if (_cacheServicesInitialized) return;
await Future.wait([
_cacheService.initialize(),
_avatarCacheService.initialize(),
_chatCacheService.initialize(),
ImageCacheService.instance.initialize(),
]);
_cacheServicesInitialized = true;
}
Future<String?> getClipboardData() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
return data?.text;

View File

@@ -105,6 +105,28 @@ extension ApiServiceChats on ApiService {
}
}
await _ensureCacheServicesInitialized();
if (!force && _lastChatsPayload == null) {
final cachedChats = await _chatCacheService.getCachedChats();
final cachedContacts = await _chatCacheService.getCachedContacts();
if (cachedChats != null &&
cachedContacts != null &&
cachedChats.isNotEmpty) {
final result = {
'chats': cachedChats,
'contacts': cachedContacts.map(_contactToMap).toList(),
'profile': null,
'presence': null,
};
_lastChatsPayload = result;
_lastChatsAt = DateTime.now();
updateContactCache(cachedContacts);
_preloadContactAvatars(cachedContacts);
return result;
}
}
try {
final payload = {"chatsCount": 100};
@@ -152,6 +174,13 @@ extension ApiServiceChats on ApiService {
contactListJson.map((json) => Contact.fromJson(json)).toList();
updateContactCache(contacts);
_lastChatsAt = DateTime.now();
_preloadContactAvatars(contacts);
unawaited(
_chatCacheService.cacheChats(
chatListJson.cast<Map<String, dynamic>>(),
),
);
unawaited(_chatCacheService.cacheContacts(contacts));
return result;
} catch (e) {
print('Ошибка получения чатов: $e');
@@ -167,12 +196,36 @@ extension ApiServiceChats on ApiService {
throw Exception("Auth token not found - please re-authenticate");
}
await _ensureCacheServicesInitialized();
if (!force && _lastChatsPayload != null && _lastChatsAt != null) {
if (DateTime.now().difference(_lastChatsAt!) < _chatsCacheTtl) {
return _lastChatsPayload!;
}
}
if (!force &&
!_chatsFetchedInThisSession &&
_lastChatsPayload == null) {
final cachedChats = await _chatCacheService.getCachedChats();
final cachedContacts = await _chatCacheService.getCachedContacts();
if (cachedChats != null &&
cachedContacts != null &&
cachedChats.isNotEmpty) {
final cachedResult = {
'chats': cachedChats,
'contacts': cachedContacts.map(_contactToMap).toList(),
'profile': null,
'presence': null,
};
_lastChatsPayload = cachedResult;
_lastChatsAt = DateTime.now();
updateContactCache(cachedContacts);
_preloadContactAvatars(cachedContacts);
return cachedResult;
}
}
if (_chatsFetchedInThisSession && _lastChatsPayload != null && !force) {
return _lastChatsPayload!;
}
@@ -232,6 +285,10 @@ extension ApiServiceChats on ApiService {
_isSessionReady = true;
_connectionStatusController.add("ready");
_updateConnectionState(
conn_state.ConnectionState.ready,
message: 'Авторизация успешна',
);
final profile = chatResponse['payload']?['profile'];
final contactProfile = profile?['contact'];
@@ -340,6 +397,13 @@ extension ApiServiceChats on ApiService {
contactListJson.map((json) => Contact.fromJson(json)).toList();
updateContactCache(contacts);
_lastChatsAt = DateTime.now();
_preloadContactAvatars(contacts);
unawaited(
_chatCacheService.cacheChats(
chatListJson.cast<Map<String, dynamic>>(),
),
);
unawaited(_chatCacheService.cacheContacts(contacts));
_chatsFetchedInThisSession = true;
_inflightChatsCompleter!.complete(result);
_inflightChatsCompleter = null;
@@ -389,11 +453,23 @@ extension ApiServiceChats on ApiService {
int chatId, {
bool force = false,
}) async {
await _ensureCacheServicesInitialized();
if (!force && _messageCache.containsKey(chatId)) {
print("Загружаем сообщения для чата $chatId из кэша.");
return _messageCache[chatId]!;
}
if (!force) {
final cachedMessages =
await _chatCacheService.getCachedChatMessages(chatId);
if (cachedMessages != null && cachedMessages.isNotEmpty) {
print("История сообщений для чата $chatId загружена из ChatCacheService.");
_messageCache[chatId] = cachedMessages;
return cachedMessages;
}
}
print("Запрашиваем историю для чата $chatId с сервера.");
final payload = {
"chatId": chatId,
@@ -433,6 +509,8 @@ extension ApiServiceChats on ApiService {
..sort((a, b) => a.time.compareTo(b.time));
_messageCache[chatId] = messagesList;
_preloadMessageImages(messagesList);
unawaited(_chatCacheService.cacheChatMessages(chatId, messagesList));
return messagesList;
} catch (e) {
@@ -567,6 +645,9 @@ extension ApiServiceChats on ApiService {
void clearCacheForChat(int chatId) {
_messageCache.remove(chatId);
if (_cacheServicesInitialized) {
unawaited(_chatCacheService.clearChatCache(chatId));
}
print("Кэш для чата $chatId очищен.");
}
@@ -651,9 +732,85 @@ extension ApiServiceChats on ApiService {
clearChatsCache();
_messageCache.clear();
clearPasswordAuthData();
if (_cacheServicesInitialized) {
unawaited(_cacheService.clear());
unawaited(_chatCacheService.clearAllChatCache());
unawaited(_avatarCacheService.clearAvatarCache());
unawaited(ImageCacheService.instance.clearCache());
}
print("Все кэши очищены из-за ошибки подключения.");
}
Future<Map<String, dynamic>> getStatistics() async {
await _ensureCacheServicesInitialized();
final cacheStats = await _cacheService.getCacheStats();
final chatCacheStats = await _chatCacheService.getChatCacheStats();
final avatarStats = await _avatarCacheService.getAvatarCacheStats();
final imageStats = await ImageCacheService.instance.getCacheStats();
return {
'api_service': {
'is_online': _isSessionOnline,
'is_ready': _isSessionReady,
'cached_chats': (_lastChatsPayload?['chats'] as List?)?.length ?? 0,
'contacts_in_memory': _contactCache.length,
'message_cache_entries': _messageCache.length,
'message_queue_length': _messageQueue.length,
},
'connection': {
'current_url': _currentUrlIndex < _wsUrls.length
? _wsUrls[_currentUrlIndex]
: null,
'reconnect_attempts': _reconnectAttempts,
'last_action_time': _lastActionTime,
},
'cache_service': cacheStats,
'chat_cache': chatCacheStats,
'avatar_cache': avatarStats,
'image_cache': imageStats,
};
}
void _preloadContactAvatars(List<Contact> contacts) {
if (!_cacheServicesInitialized || contacts.isEmpty) return;
final photoUrls = contacts.map((c) => c.photoBaseUrl).toList();
if (photoUrls.isEmpty) return;
unawaited(ImageCacheService.instance.preloadContactAvatars(photoUrls));
}
void _preloadMessageImages(List<Message> messages) {
if (!_cacheServicesInitialized || messages.isEmpty) return;
final urls = <String>{};
for (final message in messages) {
for (final attach in message.attaches) {
final url = attach['url'] ?? attach['baseUrl'];
if (url is String && url.isNotEmpty) {
urls.add(url);
}
}
}
for (final url in urls) {
unawaited(ImageCacheService.instance.preloadImage(url));
}
}
Map<String, dynamic> _contactToMap(Contact contact) {
return {
'id': contact.id,
'name': contact.name,
'firstName': contact.firstName,
'lastName': contact.lastName,
'description': contact.description,
'photoBaseUrl': contact.photoBaseUrl,
'isBlocked': contact.isBlocked,
'isBlockedByMe': contact.isBlockedByMe,
'accountStatus': contact.accountStatus,
'status': contact.status,
'options': contact.options,
};
}
void sendMessage(
int chatId,
String text, {

View File

@@ -3,6 +3,10 @@ part of 'api_service.dart';
extension ApiServiceConnection on ApiService {
Future<void> _connectWithFallback() async {
_log('Начало подключения...');
_updateConnectionState(
conn_state.ConnectionState.connecting,
message: 'Поиск доступного сервера',
);
while (_currentUrlIndex < _wsUrls.length) {
final currentUrl = _wsUrls[_currentUrlIndex];
@@ -17,6 +21,11 @@ extension ApiServiceConnection on ApiService {
? 'Подключено к основному серверу'
: 'Подключено через резервный сервер';
_connectionLogController.add('$successMessage');
_updateConnectionState(
conn_state.ConnectionState.connecting,
message: 'Соединение установлено, ожидание handshake',
metadata: {'server': currentUrl},
);
if (_currentUrlIndex > 0) {
_connectionStatusController.add('Подключено через резервный сервер');
}
@@ -25,6 +34,7 @@ extension ApiServiceConnection on ApiService {
final errorMessage = '❌ Ошибка: ${e.toString().split(':').first}';
print('Ошибка подключения к $currentUrl: $e');
_connectionLogController.add(errorMessage);
_healthMonitor.onError(errorMessage);
_currentUrlIndex++;
if (_currentUrlIndex < _wsUrls.length) {
@@ -35,12 +45,18 @@ extension ApiServiceConnection on ApiService {
_log('Все серверы недоступны');
_connectionStatusController.add('Все серверы недоступны');
_updateConnectionState(
conn_state.ConnectionState.error,
message: 'Все серверы недоступны',
);
_stopHealthMonitoring();
throw Exception('Не удалось подключиться ни к одному серверу');
}
Future<void> _connectToUrl(String url) async {
_isSessionOnline = false;
_onlineCompleter = Completer<void>();
_currentServerUrl = url;
final bool hadChatsFetched = _chatsFetchedInThisSession;
final bool hasValidToken = authToken != null;
@@ -96,6 +112,11 @@ extension ApiServiceConnection on ApiService {
print("Сессия была завершена сервером");
_isSessionOnline = false;
_isSessionReady = false;
_stopHealthMonitoring();
_updateConnectionState(
conn_state.ConnectionState.disconnected,
message: 'Сессия завершена сервером',
);
authToken = null;
@@ -111,6 +132,12 @@ extension ApiServiceConnection on ApiService {
print("Обработка недействительного токена");
_isSessionOnline = false;
_isSessionReady = false;
_stopHealthMonitoring();
_healthMonitor.onError('invalid_token');
_updateConnectionState(
conn_state.ConnectionState.error,
message: 'Недействительный токен',
);
authToken = null;
final prefs = await SharedPreferences.getInstance();
@@ -177,6 +204,10 @@ extension ApiServiceConnection on ApiService {
_isSessionReady = false;
_connectionStatusController.add("connecting");
_updateConnectionState(
conn_state.ConnectionState.connecting,
message: 'Инициализация подключения',
);
await _connectWithFallback();
}
@@ -273,6 +304,7 @@ extension ApiServiceConnection on ApiService {
try {
final decoded = jsonDecode(message) as Map<String, dynamic>;
if (decoded['opcode'] == 2) {
_healthMonitor.onPongReceived();
loggableMessage = '⬅️ RECV (pong) seq: ${decoded['seq']}';
} else {
Map<String, dynamic> loggableDecoded = Map.from(decoded);
@@ -323,6 +355,11 @@ extension ApiServiceConnection on ApiService {
_isSessionReady = false;
_reconnectDelaySeconds = 2;
_connectionStatusController.add("authorizing");
_updateConnectionState(
conn_state.ConnectionState.connected,
message: 'Handshake успешен',
);
_startHealthMonitoring();
if (_onlineCompleter != null && !_onlineCompleter!.isCompleted) {
_onlineCompleter!.complete();
@@ -334,6 +371,11 @@ extension ApiServiceConnection on ApiService {
if (decodedMessage is Map && decodedMessage['cmd'] == 3) {
final error = decodedMessage['payload'];
print('Ошибка сервера: $error');
_healthMonitor.onError(error?['message'] ?? 'server_error');
_updateConnectionState(
conn_state.ConnectionState.error,
message: error?['message'],
);
if (error != null && error['localizedMessage'] != null) {
_errorController.add(error['localizedMessage']);
@@ -557,12 +599,22 @@ extension ApiServiceConnection on ApiService {
print('Ошибка WebSocket: $error');
_isSessionOnline = false;
_isSessionReady = false;
_healthMonitor.onError(error.toString());
_updateConnectionState(
conn_state.ConnectionState.error,
message: error.toString(),
);
_reconnect();
},
onDone: () {
print('WebSocket соединение закрыто. Попытка переподключения...');
_isSessionOnline = false;
_isSessionReady = false;
_stopHealthMonitoring();
_updateConnectionState(
conn_state.ConnectionState.disconnected,
message: 'Соединение закрыто',
);
if (!_isSessionReady) {
_reconnect();
@@ -577,6 +629,7 @@ extension ApiServiceConnection on ApiService {
_isReconnecting = true;
_reconnectAttempts++;
_healthMonitor.onReconnect();
if (_reconnectAttempts > ApiService._maxReconnectAttempts) {
print(
@@ -584,6 +637,10 @@ extension ApiServiceConnection on ApiService {
);
_connectionStatusController.add("disconnected");
_isReconnecting = false;
_updateConnectionState(
conn_state.ConnectionState.error,
message: 'Превышено число попыток переподключения',
);
return;
}
@@ -607,6 +664,11 @@ extension ApiServiceConnection on ApiService {
"Переподключаемся после ${delay.inSeconds}s... (попытка $_reconnectAttempts/${ApiService._maxReconnectAttempts})",
);
_isReconnecting = false;
_updateConnectionState(
conn_state.ConnectionState.reconnecting,
attemptNumber: _reconnectAttempts,
reconnectDelay: delay,
);
_connectWithFallback();
});
}
@@ -708,6 +770,11 @@ extension ApiServiceConnection on ApiService {
_handshakeSent = false;
_onlineCompleter = Completer<void>();
_chatsFetchedInThisSession = false;
_stopHealthMonitoring();
_updateConnectionState(
conn_state.ConnectionState.disconnected,
message: 'Отключено пользователем',
);
_channel?.sink.close(status.goingAway);
_channel = null;