Skip to content

Background service to check if node goes offline #994

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 48 commits into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
130d6fc
WIP: adding notifications pgk
AlaaElattar Apr 9, 2025
2952f0e
fix ios issue and show notification with offline nodes
AlaaElattar Apr 13, 2025
783e580
remove unused import && undo changes in podfile.lock
AlaaElattar Apr 13, 2025
fd5ee16
WIP: adding permissions for android
AlaaElattar Apr 14, 2025
e7939be
WIP: downgrade background_fetch
AlaaElattar Apr 14, 2025
b8d1983
WIP: downgrade background_fetch
AlaaElattar Apr 14, 2025
d8ec42a
clear cached background_fetch
AlaaElattar Apr 14, 2025
09fcf79
specify ndk version
AlaaElattar Apr 14, 2025
039d0a7
undo nkd version setup
AlaaElattar Apr 14, 2025
79255c0
WIP: add debug logs
AlaaElattar Apr 14, 2025
7536668
WIP: debug background_fetch version
AlaaElattar Apr 14, 2025
c63e68d
update pubspec.lock
AlaaElattar Apr 14, 2025
62ac54d
update build.gradle
AlaaElattar Apr 14, 2025
e3eeef0
WIP: remove gradle cache
AlaaElattar Apr 14, 2025
e79387a
fix command
AlaaElattar Apr 14, 2025
d3aa5a1
WIP: Update build.gradle
AlaaElattar Apr 14, 2025
940a189
WIP: fix space
AlaaElattar Apr 14, 2025
2f74467
undo latest commit
AlaaElattar Apr 14, 2025
c5d36b4
add maven url in build.gradle
AlaaElattar Apr 14, 2025
58933f1
Add close button for confirmation dialog (#976)
AlaaElattar Apr 9, 2025
a719351
Handle non-loading for delete wallet (#973)
AlaaElattar Apr 9, 2025
bd2625d
Prevent PIN Entry Attempts During 30 Second Lockout Period (#989)
AlaaElattar Apr 9, 2025
d0cdb36
Fix transactions paginations (#992)
zaelgohary Apr 9, 2025
f8d3766
handle duplicated daily (#986)
AlaaElattar Apr 14, 2025
9dfcd94
Update the packages version for background_fetch & flutter_local_noti…
AhmedHanafy725 Apr 15, 2025
6a60a02
Request to enable the notification service on android
AhmedHanafy725 Apr 15, 2025
4532ecb
Revert the changes in the wrong manifest file
AhmedHanafy725 Apr 15, 2025
c4873e7
Update the gradle repos
AhmedHanafy725 Apr 15, 2025
d28d9b2
Update build gradle dependencies
AhmedHanafy725 Apr 15, 2025
d9453e7
Update the manifest permissions
AhmedHanafy725 Apr 15, 2025
d9f57dd
Merge branch 'development' into development_check_nodes
AhmedHanafy725 Apr 16, 2025
eaf9eab
only show notifications for nodes down last 2 days && group notificat…
AlaaElattar Apr 22, 2025
78a059b
remove unused import
AlaaElattar Apr 22, 2025
7bcfb88
update checking nodes for last 7 days
AlaaElattar Apr 22, 2025
01c6b32
Update app/lib/services/background_service.dart
AlaaElattar Apr 24, 2025
ff26022
apply pr comments && apply the exponential notification
AlaaElattar Apr 24, 2025
56afeb9
handle notification grouping
AlaaElattar Apr 24, 2025
69ba0e6
handled tapping on notification
AlaaElattar Apr 24, 2025
3aeeeeb
Hide show phrase (#995)
zaelgohary Apr 16, 2025
48b9cd1
Handle duplicated contacts in favorite List (#983)
AlaaElattar Apr 24, 2025
7b09e6a
Fix auth timeout routing (#1000)
zaelgohary Apr 27, 2025
b877ea9
fix ios issue and show notification with offline nodes
AlaaElattar Apr 13, 2025
ffead77
update pubspec.lock
AlaaElattar Apr 14, 2025
e0b7121
Merge branch 'development' into development_check_nodes
AlaaElattar Apr 28, 2025
4a4be60
fix workflow
AlaaElattar Apr 28, 2025
a0016f7
fix equation && workflow
AlaaElattar Apr 28, 2025
d7a1b80
undo the equation
AlaaElattar Apr 30, 2025
c2b8c0b
fixed time conversion
AlaaElattar Apr 30, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: 050ff199c8e97450c391a88d64db90da96da9995

COCOAPODS: 1.16.2
COCOAPODS: 1.16.2
18 changes: 16 additions & 2 deletions app/ios/Runner/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
import UIKit
import Flutter
import flutter_local_notifications

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}

override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
GeneratedPluginRegistrant.register(with: registry)
}

if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
}

GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)

}
}
}
14 changes: 14 additions & 0 deletions app/ios/Runner/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -86,5 +86,19 @@
<false/>
<key>io.flutter.embedded_views_preview</key>
<true/>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>remote-notification</string>
</array>

<key>NSUserNotificationAlertStyle</key>
<string>alert</string>

<key>NSLocalNetworkUsageDescription</key>
<string>This app uses the network to monitor your node status.</string>

<key>NSUserNotificationUsageDescription</key>
<string>This app needs permission to send you notifications when your node is offline.</string>
</dict>
</plist>
30 changes: 29 additions & 1 deletion app/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import 'package:background_fetch/background_fetch.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:threebotlogin/helpers/globals.dart';
import 'package:threebotlogin/helpers/logger.dart';
import 'package:threebotlogin/screens/splash_screen.dart';
import 'package:threebotlogin/services/background_service.dart';
import 'package:threebotlogin/services/notification_service.dart';
import 'package:threebotlogin/services/shared_preference_service.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:threebotlogin/providers/theme_provider.dart';
Expand Down Expand Up @@ -33,6 +37,10 @@ Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

await NotificationService().initNotification();

BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);

bool initDone = await getInitDone();
String? doubleName = await getDoubleName();

Expand All @@ -44,6 +52,27 @@ Future<void> main() async {
child: MyApp(initDone: initDone, registered: registered),
),
);

BackgroundFetch.configure(
BackgroundFetchConfig(
minimumFetchInterval: 15,
stopOnTerminate: false,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiredNetworkType: NetworkType.ANY,
),
(String taskId) async {
logger.i('[BackgroundFetch] Task: $taskId');
await checkNodeStatus();
BackgroundFetch.finish(taskId);
},
(String taskId) async {
logger.i('[BackgroundFetch] Timeout: $taskId');
BackgroundFetch.finish(taskId);
},
);
}

Future<void> setGlobalValues() async {
Expand All @@ -52,7 +81,6 @@ Future<void> setGlobalValues() async {

Globals().emailVerified.value = (email['sei'] != null);
Globals().phoneVerified.value = (phone['spi'] != null);

}

class MyApp extends ConsumerWidget {
Expand Down
29 changes: 29 additions & 0 deletions app/lib/services/background_service.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import 'package:background_fetch/background_fetch.dart';
import 'package:threebotlogin/services/nodes_check_service.dart';
import 'notification_service.dart';

void backgroundFetchHeadlessTask(HeadlessTask task) async {
final String taskId = task.taskId;
final bool timeout = task.timeout;

if (timeout) {
BackgroundFetch.finish(taskId);
return;
}
await checkNodeStatus();

BackgroundFetch.finish(taskId);
}

Future<void> checkNodeStatus() async {
final offlineNodes = await NodeCheckService.pingNodesInBackground();

if (offlineNodes.isNotEmpty) {
final nodeIds = offlineNodes.map((n) => n.nodeId).join(', ');
await NotificationService().showNotification(
title: 'Node Alert 🚨',
body: 'Offline node(s): $nodeIds',
);
}
}

55 changes: 55 additions & 0 deletions app/lib/services/nodes_check_service.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:threebotlogin/helpers/logger.dart';
import 'package:threebotlogin/models/farm.dart';
import 'package:threebotlogin/models/wallet.dart';
import 'package:threebotlogin/providers/wallets_provider.dart';
import 'package:threebotlogin/services/gridproxy_service.dart';
import 'package:threebotlogin/services/tfchain_service.dart';

class NodeCheckService {
static Future<List<Node>> pingNodesInBackground() async {
final container = ProviderContainer();
try {
final walletsNotifierInstance = container.read(walletsNotifier.notifier);

await walletsNotifierInstance.waitUntilListed();

final List<Wallet> wallets = container.read(walletsNotifier);

final Map<int, Wallet> twinIdWallets = {};
for (final wallet in wallets) {
final twinId = await getTwinId(wallet.tfchainSecret);
if (twinId != 0) {
twinIdWallets[twinId] = wallet;
}
}
final farmsList = await getFarmsByTwinIds(twinIdWallets.keys.toList());
final allNodes = <Node>[];
for (final farm in farmsList) {
final nodesData = await getNodesByFarmId(farm.farmID);

final nodes = nodesData
.map((node) => Node(
nodeId: node.nodeId,
status: NodeStatus.values.firstWhere(
(e) =>
e.toString().toLowerCase() ==
'nodestatus.${node.status.toLowerCase()}',
),
))
.toList();
allNodes.addAll(nodes);
}
final offlineNodes =
allNodes.where((n) => n.status != NodeStatus.Up).toList();

return offlineNodes;

} catch (e) {
logger.e('[NodeCheckService] Error: $e');
return [];
} finally {
container.dispose();
}
}
}
56 changes: 56 additions & 0 deletions app/lib/services/notification_service.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationService {
static final NotificationService _instance = NotificationService._internal();
factory NotificationService() => _instance;
NotificationService._internal();

final notificationsPlugin = FlutterLocalNotificationsPlugin();
bool _isInitialized = false;

Future<void> initNotification() async {
if (_isInitialized) return;

const initSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
const initSettingsIOS = DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);

const initSettings = InitializationSettings(
android: initSettingsAndroid,
iOS: initSettingsIOS,
);

await notificationsPlugin.initialize(initSettings);

_isInitialized = true;
}

NotificationDetails _notificationDetails() {
return const NotificationDetails(
android: AndroidNotificationDetails(
'node_status_channel',
'Node Status',
channelDescription: 'Notify user when node goes offline',
importance: Importance.max,
priority: Priority.high,
),
iOS: DarwinNotificationDetails(
presentAlert: true,
presentSound: true,
presentBadge: true,
),
);
}

Future<void> showNotification({
int id = 0,
required String title,
required String body,
}) async {
await notificationsPlugin.show(id, title, body, _notificationDetails());
}
}

48 changes: 48 additions & 0 deletions app/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.1.21"
background_fetch:
dependency: "direct main"
description:
name: background_fetch
sha256: "442e82f508708be89fd0cc7e1dc3b27bc7c6c8c39a47967ccb7ed1c57b9108b5"
url: "https://pub.dev"
source: hosted
version: "1.3.8"
base_x:
dependency: transitive
description:
Expand Down Expand Up @@ -595,6 +603,38 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.0"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: d59eeafd6df92174b1d5f68fc9d66634c97ce2e7cfe2293476236547bb19bbbd
url: "https://pub.dev"
source: hosted
version: "19.0.0"
flutter_local_notifications_linux:
dependency: transitive
description:
name: flutter_local_notifications_linux
sha256: e3c277b2daab8e36ac5a6820536668d07e83851aeeb79c446e525a70710770a5
url: "https://pub.dev"
source: hosted
version: "6.0.0"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: "2569b973fc9d1f63a37410a9f7c1c552081226c597190cb359ef5d5762d1631c"
url: "https://pub.dev"
source: hosted
version: "9.0.0"
flutter_local_notifications_windows:
dependency: transitive
description:
name: flutter_local_notifications_windows
sha256: f8fc0652a601f83419d623c85723a3e82ad81f92b33eaa9bcc21ea1b94773e6e
url: "https://pub.dev"
source: hosted
version: "1.0.0"
flutter_pkid:
dependency: "direct main"
description:
Expand Down Expand Up @@ -1816,6 +1856,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.7.0"
timezone:
dependency: transitive
description:
name: timezone
sha256: ffc9d5f4d1193534ef051f9254063fa53d588609418c84299956c3db9383587d
url: "https://pub.dev"
source: hosted
version: "0.10.0"
timing:
dependency: transitive
description:
Expand Down
2 changes: 2 additions & 0 deletions app/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ dependencies:
infinite_scroll_pagination: ^4.1.0
intl_mobile_field: ^1.1.1
mobile_scanner: 5.2.3
flutter_local_notifications: ^19.0.0
background_fetch: ^1.3.8
dev_dependencies:
flutter_test:
sdk: flutter
Expand Down
Loading