Skip to content

Commit

Permalink
feat: show error for disconnected
Browse files Browse the repository at this point in the history
  • Loading branch information
VincePaulin committed Nov 21, 2023
1 parent 19dc1f5 commit 1c646a7
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 40 deletions.
29 changes: 7 additions & 22 deletions lib/pages/add_bridge/add_bridge_body.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class _AddBridgeBodyState extends State<AddBridgeBody> {
Future<void> _initStateAsync() async {
try {

final instagramConnected = await _pingWithTimeout(botConnection.instagramPing());
final instagramConnected = await botConnection.pingWithTimeout(context, botConnection.instagramPing());
setState(() {
socialNetwork.firstWhere((element) => element.name == "Instagram").connected = instagramConnected;
socialNetwork.firstWhere((element) => element.name == "Instagram").loading = false;
Expand All @@ -60,24 +60,6 @@ class _AddBridgeBodyState extends State<AddBridgeBody> {

}

// Function to manage missed deadlines
Future<bool> _pingWithTimeout(Future<bool> pingFunction) async {
try {
// Future.timeout to define a maximum waiting time
return await pingFunction.timeout(const Duration(seconds: 15));
} on TimeoutException {
print("Ping timeout");

// Display error message to warn user
showCatchErrorDialog(context, L10n.of(context)!.err_timeOut);

throw TimeoutException("Ping timeout");
} catch (error) {
print("Error pinging: $error");
rethrow;
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
Expand Down Expand Up @@ -149,10 +131,13 @@ class _AddBridgeBodyState extends State<AddBridgeBody> {
setState(() {
network.connected = false;
});
}

// Show the dialog for deleting the conversation
await showDeleteConversationDialog(context, network, botConnection);
// Show the dialog for deleting the conversation
await showDeleteConversationDialog(context, network, botConnection);
}else{
// Display error message to warn user
showCatchErrorDialog(context, L10n.of(context)!.err_timeOut);
}
}
}
}
Expand Down
61 changes: 46 additions & 15 deletions lib/pages/add_bridge/service/bot_bridge_connection.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:matrix/matrix.dart';
import 'package:uuid/uuid.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';

import '../error_message_dialog.dart';

// For all bot bridge conversations
// For the moment, rooms are DirectChat
Expand Down Expand Up @@ -163,15 +169,29 @@ class BotBridgeConnection {
const String botUserId = '@instagrambot:loveto.party';

final RegExp successMatch = RegExp(r"Successfully logged out");
final RegExp aldreadyLogoutMatch = RegExp(r"That command requires you to be logged in.");

// Add a direct chat with the Instagram bot (if you haven't already)
String? directChat = client.getDirectChatFromUserId(botUserId);
directChat ??= await client.startDirectChat(botUserId);

bool result = true; // Variable to track the result of the connection

// Get the latest messages from the room (limited to the specified number)
while (true) {
// Send the "logout" message to the bot
final Map<String, Object?> messageBody = {
'msgtype': 'm.text',
'body': "logout",
};
await client.sendMessage(
directChat,
'm.room.message',
const Uuid().v4(), // Generate random txnId
messageBody,
);
await Future.delayed(const Duration(seconds: 5)); // Wait 5 sec

// Get the latest messages from the room (limited to the specified number)
final GetRoomEventsResponse response = await client.getRoomEvents(
directChat,
Direction.b, // To get the latest messages
Expand All @@ -185,20 +205,13 @@ class BotBridgeConnection {
latestMessages.first.content['body'].toString() ?? '';

// to find out if we're connected
if (!successMatch.hasMatch(latestMessage)) {
// Send the "logout" message to the bot
final Map<String, Object?> messageBody = {
'msgtype': 'm.text',
'body': "logout",
};
await client.sendMessage(
directChat,
'm.room.message',
const Uuid().v4(), // Generate random txnId
messageBody,
);
await Future.delayed(const Duration(seconds: 5)); // Wait 5 sec
} else if (successMatch.hasMatch(latestMessage)) {
if (!successMatch.hasMatch(latestMessage) &&
!aldreadyLogoutMatch.hasMatch(latestMessage)) {
print("You're always connected");
result = true;
break;
} else if (successMatch.hasMatch(latestMessage)
|| aldreadyLogoutMatch.hasMatch(latestMessage)) {
print("You're disconnected");

result = false;
Expand All @@ -224,4 +237,22 @@ class BotBridgeConnection {
print('Error deleting conversation: $e');
}
}

// Function to manage missed deadlines
Future<bool> pingWithTimeout(BuildContext context, Future<bool> pingFunction) async {
try {
// Future.timeout to define a maximum waiting time
return await pingFunction.timeout(const Duration(seconds: 15));
} on TimeoutException {
print("Ping timeout");

// Display error message to warn user
showCatchErrorDialog(context, L10n.of(context)!.err_timeOut);

throw TimeoutException("Ping timeout");
} catch (error) {
print("Error pinging: $error");
rethrow;
}
}
}
13 changes: 10 additions & 3 deletions lib/pages/add_bridge/show_bottom_sheet.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,25 @@ Future<bool> showBottomSheetBridge(
await showFutureLoadingDialog(
context: context,
future: () async {

if (network.name == "Instagram") {
result = await botConnection.disconnectToInstagram();
}

// Returns True if disconnection has been made
completer.complete(true);
if(result != false){
completer.complete(false);
}
},
);

completer.complete(true);

} catch (e) {
print("error: $e");

Navigator.of(context).pop();
//To view other catch-related errors
showCatchErrorDialog(context, e);
showCatchErrorDialog(context, L10n.of(context)!.err_timeOut);
}
},
),
Expand Down

0 comments on commit 1c646a7

Please sign in to comment.