diff --git a/lib/app.dart b/lib/app.dart index 00e3852..29a74b7 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -73,6 +73,7 @@ class _AppState extends State with WidgetsBindingObserver { Future initAsync() async { setUserPlan(); await apiService.connect(force: true); + apiService.listenToNetworkChanges(); // call this function so invalid media files are get purged retryMediaUpload(true); } diff --git a/lib/src/services/api.service.dart b/lib/src/services/api.service.dart index 61eae4d..bcb9bbf 100644 --- a/lib/src/services/api.service.dart +++ b/lib/src/services/api.service.dart @@ -3,6 +3,7 @@ import 'dart:collection'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; +import 'package:connectivity_plus/connectivity_plus.dart'; import 'package:drift/drift.dart'; import 'package:fixnum/fixnum.dart'; import 'package:flutter/foundation.dart'; @@ -56,6 +57,7 @@ class ApiService { final HashMap messagesV0 = HashMap(); IOWebSocketChannel? _channel; + StreamSubscription>? connectivitySubscription; Future _connectTo(String apiUrl) async { try { @@ -68,7 +70,11 @@ class ApiService { Log.info("websocket connected to $apiUrl"); return true; } on WebSocketChannelException catch (e) { - Log.error("could not connect to api got: $e"); + if (!e.message + .toString() + .contains("No address associated with hostname")) { + Log.error("could not connect to api got: $e"); + } return false; } } @@ -102,8 +108,11 @@ class ApiService { isAuthenticated = false; globalCallbackConnectionState(false); await twonlyDB.messagesDao.resetPendingDownloadState(); + } + + Future startReconnectionTimer() async { + reconnectionTimer?.cancel(); reconnectionTimer ??= Timer(Duration(seconds: _reconnectionDelay), () { - Log.info("starting with reconnection."); reconnectionTimer = null; connect(force: true); }); @@ -121,6 +130,20 @@ class ApiService { callback(); } + Future listenToNetworkChanges() async { + if (connectivitySubscription != null) { + return; + } + connectivitySubscription = Connectivity() + .onConnectivityChanged + .listen((List result) { + if (!result.contains(ConnectivityResult.none)) { + connect(force: true); + } + // Received changes in available connectivity types! + }); + } + Future connect({bool force = false}) async { if (reconnectionTimer != null && !force) { return false;