Skip to content
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

added check for new versions and automatically prompt the user #552

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
54 changes: 43 additions & 11 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'package:apidash/providers/update_provider.dart';
import 'package:apidash_design_system/apidash_design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
Expand All @@ -6,6 +7,10 @@ import 'providers/providers.dart';
import 'services/services.dart';
import 'consts.dart';
import 'app.dart';
import 'widgets/update_dialog.dart';
import 'dart:async';

GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

void main() async {
WidgetsFlutterBinding.ensureInitialized();
Expand All @@ -22,15 +27,46 @@ void main() async {
}

runApp(
ProviderScope(
overrides: [
settingsProvider.overrideWith(
(ref) => ThemeStateNotifier(settingsModel: settingsModel),
)
],
child: const DashApp(),
Builder(
builder: (context) {
navigatorKey = GlobalKey<NavigatorState>();
return MaterialApp(
navigatorKey: navigatorKey,
home: ProviderScope(
overrides: [
settingsProvider.overrideWith(
(ref) => ThemeStateNotifier(settingsModel: settingsModel),
)
],
child: const DashApp(),
),
);
},
),
);

// Check for updates after app launch
if (kIsDesktop) {
// Delay update check to ensure app is fully initialized
Timer(const Duration(seconds: 3), () async {
try {
final container = ProviderContainer();
final updateInfo = await container.read(updateCheckProvider.future);
if (updateInfo != null) {
if (navigatorKey.currentContext != null) {
showDialog(
context: navigatorKey.currentContext!,
builder: (context) => ProviderScope(
child: UpdateDialog(updateInfo: updateInfo),
),
);
}
}
} catch (e) {
throw('❌ Error in update check: $e');
}
});
}
}

Future<bool> initApp(
Expand All @@ -39,19 +75,15 @@ Future<bool> initApp(
}) async {
GoogleFonts.config.allowRuntimeFetching = false;
try {
debugPrint("initializeUsingPath: $initializeUsingPath");
debugPrint("workspaceFolderPath: ${settingsModel?.workspaceFolderPath}");
final openBoxesStatus = await initHiveBoxes(
initializeUsingPath,
settingsModel?.workspaceFolderPath,
);
debugPrint("openBoxesStatus: $openBoxesStatus");
if (openBoxesStatus) {
await autoClearHistory(settingsModel: settingsModel);
}
return openBoxesStatus;
} catch (e) {
debugPrint("initApp failed due to $e");
return false;
}
}
Expand Down
21 changes: 21 additions & 0 deletions lib/providers/update_provider.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../services/update_service.dart';

final updateProvider = Provider((ref) => UpdateService());

final updateCheckProvider = FutureProvider.autoDispose((ref) async {
final updateService = ref.watch(updateProvider);
return await updateService.checkForUpdate();
});

class UpdateNotifier extends StateNotifier<bool> {
UpdateNotifier() : super(false);

void setChecking(bool checking) {
state = checking;
}
}

final updateCheckingProvider = StateNotifierProvider<UpdateNotifier, bool>((ref) {
return UpdateNotifier();
});
83 changes: 83 additions & 0 deletions lib/services/update_service.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

class UpdateService {
static const String _githubApiUrl = 'https://api.github.com/repos/foss42/apidash/releases/latest';
static const String _skipVersionKey = 'skipped_version';

Future<Map<String, dynamic>?> checkForUpdate() async {
try {
// Get current app version
final packageInfo = await PackageInfo.fromPlatform();
final currentVersion = packageInfo.version;

// Fetch latest release from GitHub
final response = await http.get(Uri.parse(_githubApiUrl));

if (response.statusCode == 200) {
final data = json.decode(response.body);
final latestVersion = data['tag_name'].toString().replaceAll('v', '');

// Check shared preferences for skipped version
final prefs = await SharedPreferences.getInstance();
final skippedVersion = prefs.getString(_skipVersionKey);

// Detailed version comparison logging
final isUpdateAvailable = _shouldUpdate(currentVersion, latestVersion);

if (isUpdateAvailable && latestVersion != skippedVersion) {
return {
'currentVersion': currentVersion,
'latestVersion': latestVersion,
'assets': data['assets'],
'releaseNotes': data['body'] ?? 'No release notes available.',
};
}
}
return null;
} catch (e) {
return null;
}
}

bool _shouldUpdate(String currentVersion, String latestVersion) {

// Detailed version comparison
final current = currentVersion.split('.').map(int.parse).toList();
final latest = latestVersion.split('.').map(int.parse).toList();

// Compare each part of the version
for (var i = 0; i < current.length; i++) {
if (latest[i] > current[i]) {
return true;
}
if (latest[i] < current[i]) {
return false;
}
}

return false;
}

Future<void> skipVersion(String version) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_skipVersionKey, version);
}

Future<void> downloadAndInstallUpdate(String downloadUrl) async {
if (Platform.isWindows) {
final uri = Uri.parse(downloadUrl);
await launchUrl(uri);
} else if (Platform.isLinux) {
final uri = Uri.parse(downloadUrl);
await launchUrl(uri);
} else if (Platform.isMacOS) {
final uri = Uri.parse(downloadUrl);
await launchUrl(uri);
}
}
}
85 changes: 85 additions & 0 deletions lib/widgets/update_dialog.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/update_provider.dart';
import 'dart:io';

class UpdateDialog extends ConsumerWidget {
final Map<String, dynamic> updateInfo;

const UpdateDialog({super.key, required this.updateInfo});

@override
Widget build(BuildContext context, WidgetRef ref) {
String getPlatformAsset() {
final assets = updateInfo['assets'] as List;
String pattern = '';

if (Platform.isWindows) {
pattern = 'windows-x86_64.exe';
} else if (Platform.isLinux) {
pattern = 'linux-amd64.deb';
} else if (Platform.isMacOS) {
pattern = 'macos-x86_64.dmg';
} else if (Platform.isAndroid) {
final playStoreUrl = updateInfo['playStoreUrl'];
if (playStoreUrl != null) {
return playStoreUrl;
}
// Fallback to .apk if Play Store URL not available
pattern = 'android-arm64.apk';
} else if (Platform.isIOS) {
final appStoreUrl = updateInfo['appStoreUrl'];
if (appStoreUrl != null) {
return appStoreUrl;
}
// Fallback to .ipa if App Store URL not available
pattern = 'ios-universal.ipa';
}

final asset = assets.firstWhere(
(asset) => asset['browser_download_url'].toString().contains(pattern),
orElse: () => null,
);
return asset?['browser_download_url'] ?? '';
}

return Theme(
data: ThemeData.dark(),
child: AlertDialog(
title: const Text('Update Available'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('A new version (${updateInfo['latestVersion']}) is available.'),
const SizedBox(height: 8),
Text('Current version: ${updateInfo['currentVersion']}'),
const SizedBox(height: 16),
const Text('Release Notes:'),
Text(updateInfo['releaseNotes'] ?? 'No release notes available.'),
],
),
actions: [
TextButton(
onPressed: () {
ref.read(updateProvider).skipVersion(updateInfo['latestVersion']);
Navigator.of(context).pop();
},
child: const Text('Skip This Version'),
),
ElevatedButton(
onPressed: () async {
final downloadUrl = getPlatformAsset();
if (downloadUrl.isNotEmpty) {
await ref.read(updateProvider).downloadAndInstallUpdate(downloadUrl);
}
// ignore: use_build_context_synchronously
Navigator.of(context).pop();
},
child: const Text('Update Now'),
),
],
),
);
}
}