mirror of
https://github.com/vleeuwenmenno/supplements.git
synced 2025-09-11 18:29:12 +02:00
feat adds proper syncing feature
Signed-off-by: Menno van Leeuwen <menno@vleeuwen.me>
This commit is contained in:
@@ -6,7 +6,7 @@ import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
|
||||
import '../models/supplement.dart';
|
||||
import '../models/supplement_intake.dart';
|
||||
import '../models/sync_enums.dart';
|
||||
import 'database_sync_service.dart';
|
||||
|
||||
class DatabaseHelper {
|
||||
static const _databaseName = 'supplements.db';
|
||||
@@ -399,7 +399,43 @@ class DatabaseHelper {
|
||||
Database db = await database;
|
||||
return await db.update(
|
||||
supplementsTable,
|
||||
{'isActive': 0},
|
||||
{
|
||||
'isActive': 0,
|
||||
'isDeleted': 1,
|
||||
'lastModified': DateTime.now().toIso8601String(),
|
||||
},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> permanentlyDeleteSupplement(int id) async {
|
||||
Database db = await database;
|
||||
|
||||
// For sync compatibility, we should mark as deleted rather than completely removing
|
||||
// This prevents the supplement from reappearing during sync
|
||||
|
||||
// First mark all related intakes as deleted
|
||||
await db.update(
|
||||
intakesTable,
|
||||
{
|
||||
'isDeleted': 1,
|
||||
'lastModified': DateTime.now().toIso8601String(),
|
||||
'syncStatus': RecordSyncStatus.modified.name,
|
||||
},
|
||||
where: 'supplementId = ? AND isDeleted = ?',
|
||||
whereArgs: [id, 0],
|
||||
);
|
||||
|
||||
// Then mark the supplement as deleted instead of removing it completely
|
||||
return await db.update(
|
||||
supplementsTable,
|
||||
{
|
||||
'isDeleted': 1,
|
||||
'isActive': 0, // Also ensure it's archived
|
||||
'lastModified': DateTime.now().toIso8601String(),
|
||||
'syncStatus': RecordSyncStatus.modified.name,
|
||||
},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
@@ -411,6 +447,36 @@ class DatabaseHelper {
|
||||
return await db.insert(intakesTable, intake.toMap());
|
||||
}
|
||||
|
||||
Future<int> deleteIntake(int id) async {
|
||||
Database db = await database;
|
||||
return await db.update(
|
||||
intakesTable,
|
||||
{
|
||||
'isDeleted': 1,
|
||||
'lastModified': DateTime.now().toIso8601String(),
|
||||
},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> permanentlyDeleteIntake(int id) async {
|
||||
Database db = await database;
|
||||
|
||||
// For sync compatibility, mark as deleted rather than completely removing
|
||||
// This prevents the intake from reappearing during sync
|
||||
return await db.update(
|
||||
intakesTable,
|
||||
{
|
||||
'isDeleted': 1,
|
||||
'lastModified': DateTime.now().toIso8601String(),
|
||||
'syncStatus': RecordSyncStatus.modified.name,
|
||||
},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<SupplementIntake>> getIntakesForDate(DateTime date) async {
|
||||
Database db = await database;
|
||||
String startDate = DateTime(date.year, date.month, date.day).toIso8601String();
|
||||
@@ -477,15 +543,6 @@ class DatabaseHelper {
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<int> deleteIntake(int id) async {
|
||||
Database db = await database;
|
||||
return await db.delete(
|
||||
intakesTable,
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
// Notification tracking methods
|
||||
Future<int> trackNotification({
|
||||
required int notificationId,
|
||||
@@ -637,7 +694,7 @@ class DatabaseHelper {
|
||||
List<Map<String, dynamic>> maps = await db.query(
|
||||
supplementsTable,
|
||||
where: 'syncStatus IN (?, ?)',
|
||||
whereArgs: [SyncStatus.pending.name, SyncStatus.modified.name],
|
||||
whereArgs: [RecordSyncStatus.pending.name, RecordSyncStatus.modified.name],
|
||||
orderBy: 'lastModified ASC',
|
||||
);
|
||||
return List.generate(maps.length, (i) => Supplement.fromMap(maps[i]));
|
||||
@@ -648,7 +705,7 @@ class DatabaseHelper {
|
||||
List<Map<String, dynamic>> maps = await db.query(
|
||||
intakesTable,
|
||||
where: 'syncStatus IN (?, ?)',
|
||||
whereArgs: [SyncStatus.pending.name, SyncStatus.modified.name],
|
||||
whereArgs: [RecordSyncStatus.pending.name, RecordSyncStatus.modified.name],
|
||||
orderBy: 'lastModified ASC',
|
||||
);
|
||||
return List.generate(maps.length, (i) => SupplementIntake.fromMap(maps[i]));
|
||||
@@ -658,7 +715,7 @@ class DatabaseHelper {
|
||||
Database db = await database;
|
||||
await db.update(
|
||||
supplementsTable,
|
||||
{'syncStatus': SyncStatus.synced.name},
|
||||
{'syncStatus': RecordSyncStatus.synced.name},
|
||||
where: 'syncId = ?',
|
||||
whereArgs: [syncId],
|
||||
);
|
||||
@@ -668,7 +725,7 @@ class DatabaseHelper {
|
||||
Database db = await database;
|
||||
await db.update(
|
||||
intakesTable,
|
||||
{'syncStatus': SyncStatus.synced.name},
|
||||
{'syncStatus': RecordSyncStatus.synced.name},
|
||||
where: 'syncId = ?',
|
||||
whereArgs: [syncId],
|
||||
);
|
||||
|
520
lib/services/database_sync_service.dart
Normal file
520
lib/services/database_sync_service.dart
Normal file
@@ -0,0 +1,520 @@
|
||||
import 'dart:io' as io;
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:webdav_client/webdav_client.dart';
|
||||
|
||||
import '../models/supplement.dart';
|
||||
import '../models/supplement_intake.dart';
|
||||
import 'database_helper.dart';
|
||||
|
||||
enum SyncStatus {
|
||||
idle,
|
||||
downloading,
|
||||
merging,
|
||||
uploading,
|
||||
completed,
|
||||
error,
|
||||
}
|
||||
|
||||
// Legacy record-level sync status for models
|
||||
enum RecordSyncStatus {
|
||||
pending,
|
||||
synced,
|
||||
modified,
|
||||
}
|
||||
|
||||
class DatabaseSyncService {
|
||||
static const String _remoteDbFileName = 'supplements.db';
|
||||
|
||||
// SharedPreferences keys for persistence
|
||||
static const String _keyServerUrl = 'sync_server_url';
|
||||
static const String _keyUsername = 'sync_username';
|
||||
static const String _keyPassword = 'sync_password';
|
||||
static const String _keyRemotePath = 'sync_remote_path';
|
||||
|
||||
Client? _client;
|
||||
String? _remotePath;
|
||||
|
||||
// Store configuration values
|
||||
String? _serverUrl;
|
||||
String? _username;
|
||||
String? _password;
|
||||
String? _configuredRemotePath;
|
||||
|
||||
final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
|
||||
|
||||
SyncStatus _status = SyncStatus.idle;
|
||||
String? _lastError;
|
||||
DateTime? _lastSyncTime;
|
||||
|
||||
// Getters
|
||||
SyncStatus get status => _status;
|
||||
String? get lastError => _lastError;
|
||||
DateTime? get lastSyncTime => _lastSyncTime;
|
||||
bool get isConfigured => _client != null;
|
||||
|
||||
// Configuration getters
|
||||
String? get serverUrl => _serverUrl;
|
||||
String? get username => _username;
|
||||
String? get password => _password;
|
||||
String? get remotePath => _configuredRemotePath;
|
||||
|
||||
// Callbacks for UI updates
|
||||
Function(SyncStatus)? onStatusChanged;
|
||||
Function(String)? onError;
|
||||
Function()? onSyncCompleted;
|
||||
|
||||
DatabaseSyncService() {
|
||||
loadSavedConfiguration();
|
||||
}
|
||||
|
||||
// Load saved configuration from SharedPreferences
|
||||
Future<void> loadSavedConfiguration() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
_serverUrl = prefs.getString(_keyServerUrl);
|
||||
_username = prefs.getString(_keyUsername);
|
||||
_password = prefs.getString(_keyPassword);
|
||||
_configuredRemotePath = prefs.getString(_keyRemotePath);
|
||||
|
||||
// If we have saved configuration, set up the client
|
||||
if (_serverUrl != null && _username != null && _password != null && _configuredRemotePath != null) {
|
||||
_remotePath = _configuredRemotePath!.endsWith('/') ? _configuredRemotePath : '$_configuredRemotePath/';
|
||||
|
||||
_client = newClient(
|
||||
_serverUrl!,
|
||||
user: _username!,
|
||||
password: _password!,
|
||||
debug: kDebugMode,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Error loading saved sync configuration: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save configuration to SharedPreferences
|
||||
Future<void> _saveConfiguration() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
if (_serverUrl != null) await prefs.setString(_keyServerUrl, _serverUrl!);
|
||||
if (_username != null) await prefs.setString(_keyUsername, _username!);
|
||||
if (_password != null) await prefs.setString(_keyPassword, _password!);
|
||||
if (_configuredRemotePath != null) await prefs.setString(_keyRemotePath, _configuredRemotePath!);
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Error saving sync configuration: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void configure({
|
||||
required String serverUrl,
|
||||
required String username,
|
||||
required String password,
|
||||
required String remotePath,
|
||||
}) {
|
||||
// Store configuration values
|
||||
_serverUrl = serverUrl;
|
||||
_username = username;
|
||||
_password = password;
|
||||
_configuredRemotePath = remotePath;
|
||||
|
||||
_remotePath = remotePath.endsWith('/') ? remotePath : '$remotePath/';
|
||||
|
||||
_client = newClient(
|
||||
serverUrl,
|
||||
user: username,
|
||||
password: password,
|
||||
debug: kDebugMode,
|
||||
);
|
||||
|
||||
// Save configuration to persistent storage
|
||||
_saveConfiguration();
|
||||
}
|
||||
|
||||
Future<bool> testConnection() async {
|
||||
if (_client == null) return false;
|
||||
|
||||
try {
|
||||
await _client!.ping();
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Connection test failed: $e');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> syncDatabase() async {
|
||||
if (_client == null) {
|
||||
throw Exception('Sync not configured');
|
||||
}
|
||||
|
||||
_setStatus(SyncStatus.downloading);
|
||||
|
||||
try {
|
||||
// Step 1: Download remote database (if it exists)
|
||||
final remoteDbPath = await _downloadRemoteDatabase();
|
||||
|
||||
// Step 2: Merge databases
|
||||
_setStatus(SyncStatus.merging);
|
||||
await _mergeDatabases(remoteDbPath);
|
||||
|
||||
// Step 3: Upload merged database
|
||||
_setStatus(SyncStatus.uploading);
|
||||
await _uploadLocalDatabase();
|
||||
|
||||
// Step 4: Cleanup - for now we'll skip cleanup to avoid file issues
|
||||
// TODO: Implement proper cleanup once file operations are working
|
||||
|
||||
_lastSyncTime = DateTime.now();
|
||||
_setStatus(SyncStatus.completed);
|
||||
onSyncCompleted?.call();
|
||||
|
||||
} catch (e) {
|
||||
_lastError = e.toString();
|
||||
_setStatus(SyncStatus.error);
|
||||
onError?.call(_lastError!);
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Sync failed: $e');
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _downloadRemoteDatabase() async {
|
||||
try {
|
||||
// Check if remote database exists
|
||||
final files = await _client!.readDir(_remotePath!);
|
||||
final remoteDbExists = files.any((file) => file.name == _remoteDbFileName);
|
||||
|
||||
if (!remoteDbExists) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: No remote database found, will upload local database');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Remote database found, downloading...');
|
||||
}
|
||||
|
||||
// Download the remote database
|
||||
final remoteDbBytes = await _client!.read('$_remotePath$_remoteDbFileName');
|
||||
|
||||
// Create a temporary file path for the downloaded database
|
||||
final tempDir = await getDatabasesPath();
|
||||
final tempDbPath = join(tempDir, 'remote_supplements.db');
|
||||
|
||||
// Write the downloaded database to a temporary file
|
||||
final tempFile = io.File(tempDbPath);
|
||||
await tempFile.writeAsBytes(remoteDbBytes);
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Downloaded remote database (${remoteDbBytes.length} bytes) to: $tempDbPath');
|
||||
}
|
||||
|
||||
return tempDbPath;
|
||||
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Failed to download remote database: $e');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _mergeDatabases(String? remoteDbPath) async {
|
||||
if (remoteDbPath == null) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: No remote database to merge');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Starting database merge from: $remoteDbPath');
|
||||
}
|
||||
|
||||
final localDb = await _databaseHelper.database;
|
||||
final remoteDb = await openDatabase(remoteDbPath, readOnly: true);
|
||||
|
||||
try {
|
||||
// Check what tables exist in remote database
|
||||
if (kDebugMode) {
|
||||
final tables = await remoteDb.rawQuery("SELECT name FROM sqlite_master WHERE type='table'");
|
||||
print('SupplementsLog: Remote database tables: ${tables.map((t) => t['name']).toList()}');
|
||||
|
||||
// Count records in each table
|
||||
try {
|
||||
final supplementCount = await remoteDb.rawQuery('SELECT COUNT(*) as count FROM supplements');
|
||||
print('SupplementsLog: Remote supplements count: ${supplementCount.first['count']}');
|
||||
} catch (e) {
|
||||
print('SupplementsLog: Error counting supplements: $e');
|
||||
}
|
||||
|
||||
try {
|
||||
final intakeCount = await remoteDb.rawQuery('SELECT COUNT(*) as count FROM supplement_intakes');
|
||||
print('SupplementsLog: Remote intakes count: ${intakeCount.first['count']}');
|
||||
} catch (e) {
|
||||
print('SupplementsLog: Error counting intakes: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Merge supplements
|
||||
await _mergeSupplements(localDb, remoteDb);
|
||||
|
||||
// Merge intakes
|
||||
await _mergeIntakes(localDb, remoteDb);
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Database merge completed successfully');
|
||||
}
|
||||
|
||||
} finally {
|
||||
await remoteDb.close();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _mergeSupplements(Database localDb, Database remoteDb) async {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Starting supplement merge...');
|
||||
}
|
||||
|
||||
// Get all supplements from remote database
|
||||
final remoteMaps = await remoteDb.query('supplements');
|
||||
final remoteSupplements = remoteMaps.map((map) => Supplement.fromMap(map)).toList();
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Found ${remoteSupplements.length} supplements in remote database');
|
||||
for (final supplement in remoteSupplements) {
|
||||
print('SupplementsLog: Remote supplement: ${supplement.name} (syncId: ${supplement.syncId}, deleted: ${supplement.isDeleted})');
|
||||
}
|
||||
}
|
||||
|
||||
for (final remoteSupplement in remoteSupplements) {
|
||||
if (remoteSupplement.syncId.isEmpty) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Skipping supplement ${remoteSupplement.name} - no syncId');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find existing supplement by syncId
|
||||
final existingMaps = await localDb.query(
|
||||
'supplements',
|
||||
where: 'syncId = ?',
|
||||
whereArgs: [remoteSupplement.syncId],
|
||||
);
|
||||
|
||||
if (existingMaps.isEmpty) {
|
||||
// New supplement from remote - insert it
|
||||
if (!remoteSupplement.isDeleted) {
|
||||
final supplementToInsert = remoteSupplement.copyWith(id: null);
|
||||
await localDb.insert('supplements', supplementToInsert.toMap());
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: ✓ Inserted new supplement: ${remoteSupplement.name}');
|
||||
}
|
||||
} else {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Skipping deleted supplement: ${remoteSupplement.name}');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Existing supplement - update if remote is newer
|
||||
final existingSupplement = Supplement.fromMap(existingMaps.first);
|
||||
|
||||
if (remoteSupplement.lastModified.isAfter(existingSupplement.lastModified)) {
|
||||
final supplementToUpdate = remoteSupplement.copyWith(id: existingSupplement.id);
|
||||
await localDb.update(
|
||||
'supplements',
|
||||
supplementToUpdate.toMap(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [existingSupplement.id],
|
||||
);
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: ✓ Updated supplement: ${remoteSupplement.name}');
|
||||
}
|
||||
} else {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Local supplement ${remoteSupplement.name} is newer, keeping local version');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Supplement merge completed');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _mergeIntakes(Database localDb, Database remoteDb) async {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Starting intake merge...');
|
||||
}
|
||||
|
||||
// Get all intakes from remote database
|
||||
final remoteMaps = await remoteDb.query('supplement_intakes');
|
||||
final remoteIntakes = remoteMaps.map((map) => SupplementIntake.fromMap(map)).toList();
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Found ${remoteIntakes.length} intakes in remote database');
|
||||
}
|
||||
|
||||
for (final remoteIntake in remoteIntakes) {
|
||||
if (remoteIntake.syncId.isEmpty) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Skipping intake - no syncId');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find existing intake by syncId
|
||||
final existingMaps = await localDb.query(
|
||||
'supplement_intakes',
|
||||
where: 'syncId = ?',
|
||||
whereArgs: [remoteIntake.syncId],
|
||||
);
|
||||
|
||||
if (existingMaps.isEmpty) {
|
||||
// New intake from remote - need to find local supplement ID
|
||||
if (!remoteIntake.isDeleted) {
|
||||
final localSupplementId = await _findLocalSupplementId(localDb, remoteIntake.supplementId, remoteDb);
|
||||
if (localSupplementId != null) {
|
||||
final intakeToInsert = remoteIntake.copyWith(
|
||||
id: null,
|
||||
supplementId: localSupplementId,
|
||||
);
|
||||
await localDb.insert('supplement_intakes', intakeToInsert.toMap());
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: ✓ Inserted new intake: ${remoteIntake.syncId}');
|
||||
}
|
||||
} else {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Could not find local supplement for intake ${remoteIntake.syncId}');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Skipping deleted intake: ${remoteIntake.syncId}');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Existing intake - update if remote is newer
|
||||
final existingIntake = SupplementIntake.fromMap(existingMaps.first);
|
||||
|
||||
if (remoteIntake.lastModified.isAfter(existingIntake.lastModified)) {
|
||||
final intakeToUpdate = remoteIntake.copyWith(id: existingIntake.id);
|
||||
await localDb.update(
|
||||
'supplement_intakes',
|
||||
intakeToUpdate.toMap(),
|
||||
where: 'id = ?',
|
||||
whereArgs: [existingIntake.id],
|
||||
);
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: ✓ Updated intake: ${remoteIntake.syncId}');
|
||||
}
|
||||
} else {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Local intake ${remoteIntake.syncId} is newer, keeping local version');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Intake merge completed');
|
||||
}
|
||||
}
|
||||
|
||||
Future<int?> _findLocalSupplementId(Database localDb, int remoteSupplementId, Database remoteDb) async {
|
||||
// Get the remote supplement
|
||||
final remoteSupplementMaps = await remoteDb.query(
|
||||
'supplements',
|
||||
where: 'id = ?',
|
||||
whereArgs: [remoteSupplementId],
|
||||
);
|
||||
|
||||
if (remoteSupplementMaps.isEmpty) return null;
|
||||
|
||||
final remoteSupplement = Supplement.fromMap(remoteSupplementMaps.first);
|
||||
|
||||
// Find the local supplement with the same syncId
|
||||
final localSupplementMaps = await localDb.query(
|
||||
'supplements',
|
||||
where: 'syncId = ?',
|
||||
whereArgs: [remoteSupplement.syncId],
|
||||
);
|
||||
|
||||
if (localSupplementMaps.isEmpty) return null;
|
||||
|
||||
return localSupplementMaps.first['id'] as int;
|
||||
}
|
||||
|
||||
Future<void> _uploadLocalDatabase() async {
|
||||
try {
|
||||
// Get the local database path
|
||||
final localDb = await _databaseHelper.database;
|
||||
final dbPath = localDb.path;
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Reading database from: $dbPath');
|
||||
}
|
||||
|
||||
// Read the database file
|
||||
final dbFile = io.File(dbPath);
|
||||
if (!await dbFile.exists()) {
|
||||
throw Exception('Database file not found at: $dbPath');
|
||||
}
|
||||
|
||||
final dbBytes = await dbFile.readAsBytes();
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Database file size: ${dbBytes.length} bytes');
|
||||
}
|
||||
|
||||
if (dbBytes.isEmpty) {
|
||||
throw Exception('Database file is empty');
|
||||
}
|
||||
|
||||
// Ensure remote directory exists
|
||||
try {
|
||||
await _client!.readDir(_remotePath!);
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Creating remote directory: $_remotePath');
|
||||
}
|
||||
await _client!.mkdir(_remotePath!);
|
||||
}
|
||||
|
||||
// Upload the database file
|
||||
final remoteUrl = '$_remotePath$_remoteDbFileName';
|
||||
await _client!.write(remoteUrl, dbBytes);
|
||||
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Successfully uploaded database (${dbBytes.length} bytes) to: $remoteUrl');
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('SupplementsLog: Failed to upload database: $e');
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
void _setStatus(SyncStatus status) {
|
||||
_status = status;
|
||||
onStatusChanged?.call(status);
|
||||
}
|
||||
|
||||
void clearError() {
|
||||
_lastError = null;
|
||||
}
|
||||
}
|
@@ -7,17 +7,17 @@ import 'database_helper.dart';
|
||||
// Top-level function to handle notification responses when app is running
|
||||
@pragma('vm:entry-point')
|
||||
void notificationTapBackground(NotificationResponse notificationResponse) {
|
||||
print('📱 === BACKGROUND NOTIFICATION RESPONSE ===');
|
||||
print('📱 Action ID: ${notificationResponse.actionId}');
|
||||
print('📱 Payload: ${notificationResponse.payload}');
|
||||
print('📱 Notification ID: ${notificationResponse.id}');
|
||||
print('📱 ==========================================');
|
||||
print('SupplementsLog: 📱 === BACKGROUND NOTIFICATION RESPONSE ===');
|
||||
print('SupplementsLog: 📱 Action ID: ${notificationResponse.actionId}');
|
||||
print('SupplementsLog: 📱 Payload: ${notificationResponse.payload}');
|
||||
print('SupplementsLog: 📱 Notification ID: ${notificationResponse.id}');
|
||||
print('SupplementsLog: 📱 ==========================================');
|
||||
|
||||
// For now, just log the action. The main app handler will process it.
|
||||
if (notificationResponse.actionId == 'take_supplement') {
|
||||
print('📱 BACKGROUND: Take action detected');
|
||||
print('SupplementsLog: 📱 BACKGROUND: Take action detected');
|
||||
} else if (notificationResponse.actionId == 'snooze_10') {
|
||||
print('📱 BACKGROUND: Snooze action detected');
|
||||
print('SupplementsLog: 📱 BACKGROUND: Snooze action detected');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,25 +40,25 @@ class NotificationService {
|
||||
}
|
||||
|
||||
Future<void> initialize() async {
|
||||
print('📱 Initializing NotificationService...');
|
||||
print('SupplementsLog: 📱 Initializing NotificationService...');
|
||||
if (_isInitialized) {
|
||||
print('📱 Already initialized');
|
||||
print('SupplementsLog: 📱 Already initialized');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
print('📱 Initializing timezones...');
|
||||
print('📱 Engine initialized flag: $_engineInitialized');
|
||||
print('SupplementsLog: 📱 Initializing timezones...');
|
||||
print('SupplementsLog: 📱 Engine initialized flag: $_engineInitialized');
|
||||
|
||||
if (!_engineInitialized) {
|
||||
tz.initializeTimeZones();
|
||||
_engineInitialized = true;
|
||||
print('📱 Timezones initialized successfully');
|
||||
print('SupplementsLog: 📱 Timezones initialized successfully');
|
||||
} else {
|
||||
print('📱 Timezones already initialized, skipping');
|
||||
print('SupplementsLog: 📱 Timezones already initialized, skipping');
|
||||
}
|
||||
} catch (e) {
|
||||
print('📱 Warning: Timezone initialization issue (may already be initialized): $e');
|
||||
print('SupplementsLog: 📱 Warning: Timezone initialization issue (may already be initialized): $e');
|
||||
_engineInitialized = true; // Mark as initialized to prevent retry
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ class NotificationService {
|
||||
try {
|
||||
// First try using the system timezone name
|
||||
final String timeZoneName = DateTime.now().timeZoneName;
|
||||
print('📱 System timezone name: $timeZoneName');
|
||||
print('SupplementsLog: 📱 System timezone name: $timeZoneName');
|
||||
|
||||
tz.Location? location;
|
||||
|
||||
@@ -80,22 +80,22 @@ class NotificationService {
|
||||
try {
|
||||
location = tz.getLocation(timeZoneName);
|
||||
} catch (e) {
|
||||
print('📱 Could not find timezone $timeZoneName, using Europe/Amsterdam as default');
|
||||
print('SupplementsLog: 📱 Could not find timezone $timeZoneName, using Europe/Amsterdam as default');
|
||||
location = tz.getLocation('Europe/Amsterdam');
|
||||
}
|
||||
}
|
||||
|
||||
tz.setLocalLocation(location);
|
||||
print('📱 Timezone set to: ${location.name}');
|
||||
print('SupplementsLog: 📱 Timezone set to: ${location.name}');
|
||||
|
||||
} catch (e) {
|
||||
print('📱 Error setting timezone: $e, using default');
|
||||
print('SupplementsLog: 📱 Error setting timezone: $e, using default');
|
||||
// Fallback to a reasonable default for Netherlands
|
||||
tz.setLocalLocation(tz.getLocation('Europe/Amsterdam'));
|
||||
}
|
||||
|
||||
print('📱 Current local time: ${tz.TZDateTime.now(tz.local)}');
|
||||
print('📱 Current system time: ${DateTime.now()}');
|
||||
print('SupplementsLog: 📱 Current local time: ${tz.TZDateTime.now(tz.local)}');
|
||||
print('SupplementsLog: 📱 Current system time: ${DateTime.now()}');
|
||||
|
||||
const AndroidInitializationSettings androidSettings = AndroidInitializationSettings('@mipmap/ic_launcher');
|
||||
const DarwinInitializationSettings iosSettings = DarwinInitializationSettings(
|
||||
@@ -113,7 +113,7 @@ class NotificationService {
|
||||
linux: linuxSettings,
|
||||
);
|
||||
|
||||
print('📱 Initializing flutter_local_notifications...');
|
||||
print('SupplementsLog: 📱 Initializing flutter_local_notifications...');
|
||||
await _notifications.initialize(
|
||||
initSettings,
|
||||
onDidReceiveNotificationResponse: _onNotificationResponse,
|
||||
@@ -121,42 +121,42 @@ class NotificationService {
|
||||
);
|
||||
|
||||
// Test if notification response callback is working
|
||||
print('📱 Callback function is set and ready');
|
||||
print('SupplementsLog: 📱 Callback function is set and ready');
|
||||
|
||||
_isInitialized = true;
|
||||
print('📱 NotificationService initialization complete');
|
||||
print('SupplementsLog: 📱 NotificationService initialization complete');
|
||||
}
|
||||
|
||||
// Handle notification responses (when user taps on notification or action)
|
||||
void _onNotificationResponse(NotificationResponse response) {
|
||||
print('📱 === NOTIFICATION RESPONSE ===');
|
||||
print('📱 Action ID: ${response.actionId}');
|
||||
print('📱 Payload: ${response.payload}');
|
||||
print('📱 Notification ID: ${response.id}');
|
||||
print('📱 Input: ${response.input}');
|
||||
print('📱 ===============================');
|
||||
print('SupplementsLog: 📱 === NOTIFICATION RESPONSE ===');
|
||||
print('SupplementsLog: 📱 Action ID: ${response.actionId}');
|
||||
print('SupplementsLog: 📱 Payload: ${response.payload}');
|
||||
print('SupplementsLog: 📱 Notification ID: ${response.id}');
|
||||
print('SupplementsLog: 📱 Input: ${response.input}');
|
||||
print('SupplementsLog: 📱 ===============================');
|
||||
|
||||
if (response.actionId == 'take_supplement') {
|
||||
print('📱 Processing TAKE action...');
|
||||
print('SupplementsLog: 📱 Processing TAKE action...');
|
||||
_handleTakeAction(response.payload, response.id);
|
||||
} else if (response.actionId == 'snooze_10') {
|
||||
print('📱 Processing SNOOZE action...');
|
||||
print('SupplementsLog: 📱 Processing SNOOZE action...');
|
||||
_handleSnoozeAction(response.payload, 10, response.id);
|
||||
} else {
|
||||
print('📱 Default notification tap (no specific action)');
|
||||
print('SupplementsLog: 📱 Default notification tap (no specific action)');
|
||||
// Default tap (no actionId) opens the app normally
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _handleTakeAction(String? payload, int? notificationId) async {
|
||||
print('📱 === HANDLING TAKE ACTION ===');
|
||||
print('📱 Payload received: $payload');
|
||||
print('SupplementsLog: 📱 === HANDLING TAKE ACTION ===');
|
||||
print('SupplementsLog: 📱 Payload received: $payload');
|
||||
|
||||
if (payload != null) {
|
||||
try {
|
||||
// Parse the payload to get supplement info
|
||||
final parts = payload.split('|');
|
||||
print('📱 Payload parts: $parts (length: ${parts.length})');
|
||||
print('SupplementsLog: 📱 Payload parts: $parts (length: ${parts.length})');
|
||||
|
||||
if (parts.length >= 4) {
|
||||
final supplementId = int.parse(parts[0]);
|
||||
@@ -164,24 +164,24 @@ class NotificationService {
|
||||
final units = double.parse(parts[2]);
|
||||
final unitType = parts[3];
|
||||
|
||||
print('📱 Parsed data:');
|
||||
print('📱 - ID: $supplementId');
|
||||
print('📱 - Name: $supplementName');
|
||||
print('📱 - Units: $units');
|
||||
print('📱 - Type: $unitType');
|
||||
print('SupplementsLog: 📱 Parsed data:');
|
||||
print('SupplementsLog: 📱 - ID: $supplementId');
|
||||
print('SupplementsLog: 📱 - Name: $supplementName');
|
||||
print('SupplementsLog: 📱 - Units: $units');
|
||||
print('SupplementsLog: 📱 - Type: $unitType');
|
||||
|
||||
// Call the callback to record the intake
|
||||
if (_onTakeSupplementCallback != null) {
|
||||
print('📱 Calling supplement callback...');
|
||||
print('SupplementsLog: 📱 Calling supplement callback...');
|
||||
_onTakeSupplementCallback!(supplementId, supplementName, units, unitType);
|
||||
print('📱 Callback completed');
|
||||
print('SupplementsLog: 📱 Callback completed');
|
||||
} else {
|
||||
print('📱 ERROR: No callback registered!');
|
||||
print('SupplementsLog: 📱 ERROR: No callback registered!');
|
||||
}
|
||||
|
||||
// Mark notification as taken in database (this will cancel any pending retries)
|
||||
if (notificationId != null) {
|
||||
print('📱 Marking notification $notificationId as taken');
|
||||
print('SupplementsLog: 📱 Marking notification $notificationId as taken');
|
||||
await DatabaseHelper.instance.markNotificationTaken(notificationId);
|
||||
|
||||
// Cancel any pending retry notifications for this notification
|
||||
@@ -189,21 +189,21 @@ class NotificationService {
|
||||
}
|
||||
|
||||
// Show a confirmation notification
|
||||
print('📱 Showing confirmation notification...');
|
||||
print('SupplementsLog: 📱 Showing confirmation notification...');
|
||||
showInstantNotification(
|
||||
'Supplement Taken!',
|
||||
'$supplementName has been recorded at ${DateTime.now().hour.toString().padLeft(2, '0')}:${DateTime.now().minute.toString().padLeft(2, '0')}',
|
||||
);
|
||||
} else {
|
||||
print('📱 ERROR: Invalid payload format - not enough parts');
|
||||
print('SupplementsLog: 📱 ERROR: Invalid payload format - not enough parts');
|
||||
}
|
||||
} catch (e) {
|
||||
print('📱 ERROR in _handleTakeAction: $e');
|
||||
print('SupplementsLog: 📱 ERROR in _handleTakeAction: $e');
|
||||
}
|
||||
} else {
|
||||
print('📱 ERROR: Payload is null');
|
||||
print('SupplementsLog: 📱 ERROR: Payload is null');
|
||||
}
|
||||
print('📱 === TAKE ACTION COMPLETE ===');
|
||||
print('SupplementsLog: 📱 === TAKE ACTION COMPLETE ===');
|
||||
}
|
||||
|
||||
void _cancelRetryNotifications(int notificationId) {
|
||||
@@ -211,13 +211,13 @@ class NotificationService {
|
||||
for (int i = 0; i < 10; i++) { // Cancel up to 10 potential retries
|
||||
int retryId = 200000 + (notificationId * 10) + i;
|
||||
_notifications.cancel(retryId);
|
||||
print('📱 Cancelled retry notification ID: $retryId');
|
||||
print('SupplementsLog: 📱 Cancelled retry notification ID: $retryId');
|
||||
}
|
||||
}
|
||||
|
||||
void _handleSnoozeAction(String? payload, int minutes, int? notificationId) {
|
||||
print('📱 === HANDLING SNOOZE ACTION ===');
|
||||
print('📱 Payload: $payload, Minutes: $minutes');
|
||||
print('SupplementsLog: 📱 === HANDLING SNOOZE ACTION ===');
|
||||
print('SupplementsLog: 📱 Payload: $payload, Minutes: $minutes');
|
||||
|
||||
if (payload != null) {
|
||||
try {
|
||||
@@ -226,17 +226,17 @@ class NotificationService {
|
||||
final supplementId = int.parse(parts[0]);
|
||||
final supplementName = parts[1];
|
||||
|
||||
print('📱 Snoozing supplement for $minutes minutes: $supplementName');
|
||||
print('SupplementsLog: 📱 Snoozing supplement for $minutes minutes: $supplementName');
|
||||
|
||||
// Mark notification as snoozed in database (increment retry count)
|
||||
if (notificationId != null) {
|
||||
print('📱 Incrementing retry count for notification $notificationId');
|
||||
print('SupplementsLog: 📱 Incrementing retry count for notification $notificationId');
|
||||
DatabaseHelper.instance.incrementRetryCount(notificationId);
|
||||
}
|
||||
|
||||
// Schedule a new notification for the snooze time
|
||||
final snoozeTime = tz.TZDateTime.now(tz.local).add(Duration(minutes: minutes));
|
||||
print('📱 Snooze time: $snoozeTime');
|
||||
print('SupplementsLog: 📱 Snooze time: $snoozeTime');
|
||||
|
||||
_notifications.zonedSchedule(
|
||||
supplementId * 1000 + minutes, // Unique ID for snooze notifications
|
||||
@@ -271,13 +271,13 @@ class NotificationService {
|
||||
'Reminder Snoozed',
|
||||
'$supplementName reminder snoozed for $minutes minutes',
|
||||
);
|
||||
print('📱 Snooze scheduled successfully');
|
||||
print('SupplementsLog: 📱 Snooze scheduled successfully');
|
||||
}
|
||||
} catch (e) {
|
||||
print('📱 Error handling snooze action: $e');
|
||||
print('SupplementsLog: 📱 Error handling snooze action: $e');
|
||||
}
|
||||
}
|
||||
print('📱 === SNOOZE ACTION COMPLETE ===');
|
||||
print('SupplementsLog: 📱 === SNOOZE ACTION COMPLETE ===');
|
||||
}
|
||||
|
||||
/// Check for persistent reminders from app context with settings
|
||||
@@ -299,19 +299,19 @@ class NotificationService {
|
||||
required int reminderRetryInterval,
|
||||
required int maxRetryAttempts,
|
||||
}) async {
|
||||
print('📱 Checking for pending notifications to retry...');
|
||||
print('SupplementsLog: 📱 Checking for pending notifications to retry...');
|
||||
|
||||
try {
|
||||
if (!persistentReminders) {
|
||||
print('📱 Persistent reminders disabled');
|
||||
print('SupplementsLog: 📱 Persistent reminders disabled');
|
||||
return;
|
||||
}
|
||||
|
||||
print('📱 Retry settings: interval=$reminderRetryInterval min, max=$maxRetryAttempts attempts');
|
||||
print('SupplementsLog: 📱 Retry settings: interval=$reminderRetryInterval min, max=$maxRetryAttempts attempts');
|
||||
|
||||
// Get all pending notifications from database
|
||||
final pendingNotifications = await DatabaseHelper.instance.getPendingNotifications();
|
||||
print('📱 Found ${pendingNotifications.length} pending notifications');
|
||||
print('SupplementsLog: 📱 Found ${pendingNotifications.length} pending notifications');
|
||||
|
||||
final now = DateTime.now();
|
||||
|
||||
@@ -326,17 +326,17 @@ class NotificationService {
|
||||
final timeSinceScheduled = now.difference(scheduledTime).inMinutes;
|
||||
final shouldRetry = timeSinceScheduled >= reminderRetryInterval;
|
||||
|
||||
print('📱 Checking notification ${notification['notificationId']}:');
|
||||
print('📱 Scheduled: $scheduledTime (local)');
|
||||
print('📱 Now: $now');
|
||||
print('📱 Time since scheduled: $timeSinceScheduled minutes');
|
||||
print('📱 Retry interval: $reminderRetryInterval minutes');
|
||||
print('📱 Should retry: $shouldRetry');
|
||||
print('📱 Retry count: $retryCount / $maxRetryAttempts');
|
||||
print('SupplementsLog: 📱 Checking notification ${notification['notificationId']}:');
|
||||
print('SupplementsLog: 📱 Scheduled: $scheduledTime (local)');
|
||||
print('SupplementsLog: 📱 Now: $now');
|
||||
print('SupplementsLog: 📱 Time since scheduled: $timeSinceScheduled minutes');
|
||||
print('SupplementsLog: 📱 Retry interval: $reminderRetryInterval minutes');
|
||||
print('SupplementsLog: 📱 Should retry: $shouldRetry');
|
||||
print('SupplementsLog: 📱 Retry count: $retryCount / $maxRetryAttempts');
|
||||
|
||||
// Check if we haven't exceeded max retry attempts
|
||||
if (retryCount >= maxRetryAttempts) {
|
||||
print('📱 Notification ${notification['notificationId']} exceeded max attempts ($maxRetryAttempts)');
|
||||
print('SupplementsLog: 📱 Notification ${notification['notificationId']} exceeded max attempts ($maxRetryAttempts)');
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -344,20 +344,20 @@ class NotificationService {
|
||||
if (lastRetryTime != null) {
|
||||
final timeSinceLastRetry = now.difference(lastRetryTime).inMinutes;
|
||||
if (timeSinceLastRetry < reminderRetryInterval) {
|
||||
print('📱 Notification ${notification['notificationId']} not ready for retry yet');
|
||||
print('SupplementsLog: 📱 Notification ${notification['notificationId']} not ready for retry yet');
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldRetry) {
|
||||
print('📱 ⚡ SCHEDULING RETRY for notification ${notification['notificationId']}');
|
||||
print('SupplementsLog: 📱 ⚡ SCHEDULING RETRY for notification ${notification['notificationId']}');
|
||||
await _scheduleRetryNotification(notification, retryCount + 1);
|
||||
} else {
|
||||
print('📱 ⏸️ NOT READY FOR RETRY: ${notification['notificationId']}');
|
||||
print('SupplementsLog: 📱 ⏸️ NOT READY FOR RETRY: ${notification['notificationId']}');
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print('📱 Error scheduling persistent reminders: $e');
|
||||
print('SupplementsLog: 📱 Error scheduling persistent reminders: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,7 +369,7 @@ class NotificationService {
|
||||
// Generate a unique ID for this retry (200000 + original_id * 10 + retry_attempt)
|
||||
final retryNotificationId = 200000 + (notificationId * 10) + retryAttempt;
|
||||
|
||||
print('📱 Scheduling retry notification $retryNotificationId for supplement $supplementId (attempt $retryAttempt)');
|
||||
print('SupplementsLog: 📱 Scheduling retry notification $retryNotificationId for supplement $supplementId (attempt $retryAttempt)');
|
||||
|
||||
// Get supplement details from database
|
||||
final supplements = await DatabaseHelper.instance.getAllSupplements();
|
||||
@@ -408,16 +408,16 @@ class NotificationService {
|
||||
// Update the retry count in database
|
||||
await DatabaseHelper.instance.incrementRetryCount(notificationId);
|
||||
|
||||
print('📱 Retry notification scheduled successfully');
|
||||
print('SupplementsLog: 📱 Retry notification scheduled successfully');
|
||||
} catch (e) {
|
||||
print('📱 Error scheduling retry notification: $e');
|
||||
print('SupplementsLog: 📱 Error scheduling retry notification: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> requestPermissions() async {
|
||||
print('📱 Requesting notification permissions...');
|
||||
print('SupplementsLog: 📱 Requesting notification permissions...');
|
||||
if (_permissionsRequested) {
|
||||
print('📱 Permissions already requested');
|
||||
print('SupplementsLog: 📱 Permissions already requested');
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -426,9 +426,9 @@ class NotificationService {
|
||||
|
||||
final androidPlugin = _notifications.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>();
|
||||
if (androidPlugin != null) {
|
||||
print('📱 Requesting Android permissions...');
|
||||
print('SupplementsLog: 📱 Requesting Android permissions...');
|
||||
final granted = await androidPlugin.requestNotificationsPermission();
|
||||
print('📱 Android permissions granted: $granted');
|
||||
print('SupplementsLog: 📱 Android permissions granted: $granted');
|
||||
if (granted != true) {
|
||||
_permissionsRequested = false;
|
||||
return false;
|
||||
@@ -437,31 +437,31 @@ class NotificationService {
|
||||
|
||||
final iosPlugin = _notifications.resolvePlatformSpecificImplementation<IOSFlutterLocalNotificationsPlugin>();
|
||||
if (iosPlugin != null) {
|
||||
print('📱 Requesting iOS permissions...');
|
||||
print('SupplementsLog: 📱 Requesting iOS permissions...');
|
||||
final granted = await iosPlugin.requestPermissions(
|
||||
alert: true,
|
||||
badge: true,
|
||||
sound: true,
|
||||
);
|
||||
print('📱 iOS permissions granted: $granted');
|
||||
print('SupplementsLog: 📱 iOS permissions granted: $granted');
|
||||
if (granted != true) {
|
||||
_permissionsRequested = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
print('📱 All permissions granted successfully');
|
||||
print('SupplementsLog: 📱 All permissions granted successfully');
|
||||
return true;
|
||||
} catch (e) {
|
||||
_permissionsRequested = false;
|
||||
print('📱 Error requesting permissions: $e');
|
||||
print('SupplementsLog: 📱 Error requesting permissions: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> scheduleSupplementReminders(Supplement supplement) async {
|
||||
print('📱 Scheduling reminders for ${supplement.name}');
|
||||
print('📱 Reminder times: ${supplement.reminderTimes}');
|
||||
print('SupplementsLog: 📱 Scheduling reminders for ${supplement.name}');
|
||||
print('SupplementsLog: 📱 Reminder times: ${supplement.reminderTimes}');
|
||||
|
||||
// Cancel existing notifications for this supplement
|
||||
await cancelSupplementReminders(supplement.id!);
|
||||
@@ -475,7 +475,7 @@ class NotificationService {
|
||||
final notificationId = supplement.id! * 100 + i; // Unique ID for each reminder
|
||||
final scheduledTime = _nextInstanceOfTime(hour, minute);
|
||||
|
||||
print('📱 Scheduling notification ID $notificationId for ${timeStr} -> ${scheduledTime}');
|
||||
print('SupplementsLog: 📱 Scheduling notification ID $notificationId for ${timeStr} -> ${scheduledTime}');
|
||||
|
||||
// Track this notification in the database
|
||||
await DatabaseHelper.instance.trackNotification(
|
||||
@@ -518,14 +518,14 @@ class NotificationService {
|
||||
payload: '${supplement.id}|${supplement.name}|${supplement.numberOfUnits}|${supplement.unitType}',
|
||||
);
|
||||
|
||||
print('📱 Successfully scheduled notification ID $notificationId');
|
||||
print('SupplementsLog: 📱 Successfully scheduled notification ID $notificationId');
|
||||
}
|
||||
|
||||
// Get all pending notifications to verify
|
||||
final pendingNotifications = await _notifications.pendingNotificationRequests();
|
||||
print('📱 Total pending notifications: ${pendingNotifications.length}');
|
||||
print('SupplementsLog: 📱 Total pending notifications: ${pendingNotifications.length}');
|
||||
for (final notification in pendingNotifications) {
|
||||
print('📱 Pending: ID=${notification.id}, Title=${notification.title}');
|
||||
print('SupplementsLog: 📱 Pending: ID=${notification.id}, Title=${notification.title}');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,22 +548,22 @@ class NotificationService {
|
||||
final tz.TZDateTime now = tz.TZDateTime.now(tz.local);
|
||||
tz.TZDateTime scheduledDate = tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, minute);
|
||||
|
||||
print('📱 Current time: $now (${now.timeZoneName})');
|
||||
print('📱 Target time: ${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}');
|
||||
print('📱 Initial scheduled date: $scheduledDate (${scheduledDate.timeZoneName})');
|
||||
print('SupplementsLog: 📱 Current time: $now (${now.timeZoneName})');
|
||||
print('SupplementsLog: 📱 Target time: ${hour.toString().padLeft(2, '0')}:${minute.toString().padLeft(2, '0')}');
|
||||
print('SupplementsLog: 📱 Initial scheduled date: $scheduledDate (${scheduledDate.timeZoneName})');
|
||||
|
||||
if (scheduledDate.isBefore(now)) {
|
||||
scheduledDate = scheduledDate.add(const Duration(days: 1));
|
||||
print('📱 Time has passed, scheduling for tomorrow: $scheduledDate (${scheduledDate.timeZoneName})');
|
||||
print('SupplementsLog: 📱 Time has passed, scheduling for tomorrow: $scheduledDate (${scheduledDate.timeZoneName})');
|
||||
} else {
|
||||
print('📱 Time is in the future, scheduling for today: $scheduledDate (${scheduledDate.timeZoneName})');
|
||||
print('SupplementsLog: 📱 Time is in the future, scheduling for today: $scheduledDate (${scheduledDate.timeZoneName})');
|
||||
}
|
||||
|
||||
return scheduledDate;
|
||||
}
|
||||
|
||||
Future<void> showInstantNotification(String title, String body) async {
|
||||
print('📱 Showing instant notification: $title - $body');
|
||||
print('SupplementsLog: 📱 Showing instant notification: $title - $body');
|
||||
const NotificationDetails notificationDetails = NotificationDetails(
|
||||
android: AndroidNotificationDetails(
|
||||
'instant_notifications',
|
||||
@@ -581,22 +581,22 @@ class NotificationService {
|
||||
body,
|
||||
notificationDetails,
|
||||
);
|
||||
print('📱 Instant notification sent');
|
||||
print('SupplementsLog: 📱 Instant notification sent');
|
||||
}
|
||||
|
||||
// Debug function to test notifications
|
||||
Future<void> testNotification() async {
|
||||
print('📱 Testing notification system...');
|
||||
print('SupplementsLog: 📱 Testing notification system...');
|
||||
await showInstantNotification('Test Notification', 'This is a test notification to verify the system is working.');
|
||||
}
|
||||
|
||||
// Debug function to schedule a test notification 1 minute from now
|
||||
Future<void> testScheduledNotification() async {
|
||||
print('📱 Testing scheduled notification...');
|
||||
print('SupplementsLog: 📱 Testing scheduled notification...');
|
||||
final now = tz.TZDateTime.now(tz.local);
|
||||
final testTime = now.add(const Duration(minutes: 1));
|
||||
|
||||
print('📱 Scheduling test notification for: $testTime');
|
||||
print('SupplementsLog: 📱 Scheduling test notification for: $testTime');
|
||||
|
||||
await _notifications.zonedSchedule(
|
||||
99999, // Special ID for test notifications
|
||||
@@ -616,7 +616,7 @@ class NotificationService {
|
||||
androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
|
||||
);
|
||||
|
||||
print('📱 Test notification scheduled successfully');
|
||||
print('SupplementsLog: 📱 Test notification scheduled successfully');
|
||||
}
|
||||
|
||||
// Debug function to get all pending notifications
|
||||
@@ -626,7 +626,7 @@ class NotificationService {
|
||||
|
||||
// Debug function to test notification actions
|
||||
Future<void> testNotificationWithActions() async {
|
||||
print('📱 Creating test notification with actions...');
|
||||
print('SupplementsLog: 📱 Creating test notification with actions...');
|
||||
|
||||
await _notifications.show(
|
||||
88888, // Special test ID
|
||||
@@ -659,12 +659,12 @@ class NotificationService {
|
||||
payload: '999|Test Supplement|1.0|capsule',
|
||||
);
|
||||
|
||||
print('📱 Test notification with actions created');
|
||||
print('SupplementsLog: 📱 Test notification with actions created');
|
||||
}
|
||||
|
||||
// Debug function to test basic notification tap response
|
||||
Future<void> testBasicNotification() async {
|
||||
print('📱 Creating basic test notification...');
|
||||
print('SupplementsLog: 📱 Creating basic test notification...');
|
||||
|
||||
await _notifications.show(
|
||||
77777, // Special test ID for basic notification
|
||||
@@ -683,6 +683,6 @@ class NotificationService {
|
||||
payload: 'basic_test',
|
||||
);
|
||||
|
||||
print('📱 Basic test notification created');
|
||||
print('SupplementsLog: 📱 Basic test notification created');
|
||||
}
|
||||
}
|
||||
|
@@ -1,928 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:connectivity_plus/connectivity_plus.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:webdav_client/webdav_client.dart';
|
||||
|
||||
import '../models/supplement.dart';
|
||||
import '../models/supplement_intake.dart';
|
||||
import '../models/sync_data.dart';
|
||||
import '../models/sync_enums.dart';
|
||||
import 'database_helper.dart';
|
||||
|
||||
/// Service for handling WebDAV synchronization operations
|
||||
class WebDAVSyncService {
|
||||
static const String _baseUrlKey = 'webdav_base_url';
|
||||
static const String _usernameKey = 'webdav_username';
|
||||
static const String _passwordKey = 'webdav_password';
|
||||
static const String _deviceNameKey = 'webdav_device_name';
|
||||
static const String _deviceIdKey = 'webdav_device_id';
|
||||
static const String _lastSyncTimeKey = 'webdav_last_sync_time';
|
||||
static const String _lastWorkingUrlKey = 'webdav_last_working_url';
|
||||
static const String _syncFolderNameKey = 'webdav_sync_folder_name';
|
||||
|
||||
final FlutterSecureStorage _secureStorage = const FlutterSecureStorage(
|
||||
aOptions: AndroidOptions(
|
||||
encryptedSharedPreferences: true,
|
||||
),
|
||||
iOptions: IOSOptions(
|
||||
accessibility: KeychainAccessibility.first_unlock_this_device,
|
||||
),
|
||||
);
|
||||
|
||||
final DatabaseHelper _databaseHelper = DatabaseHelper.instance;
|
||||
final Connectivity _connectivity = Connectivity();
|
||||
|
||||
Client? _webdavClient;
|
||||
String? _currentDeviceId;
|
||||
String? _currentDeviceName;
|
||||
String? _syncFolderName;
|
||||
|
||||
/// Initialize the service and generate device ID if needed
|
||||
Future<void> initialize() async {
|
||||
await _ensureDeviceInfo();
|
||||
_syncFolderName = await getSyncFolderName();
|
||||
}
|
||||
|
||||
/// Check if WebDAV is configured
|
||||
Future<bool> isConfigured() async {
|
||||
final baseUrl = await _secureStorage.read(key: _baseUrlKey);
|
||||
final username = await _secureStorage.read(key: _usernameKey);
|
||||
final password = await _secureStorage.read(key: _passwordKey);
|
||||
|
||||
return baseUrl != null &&
|
||||
baseUrl.isNotEmpty &&
|
||||
username != null &&
|
||||
username.isNotEmpty &&
|
||||
password != null &&
|
||||
password.isNotEmpty;
|
||||
}
|
||||
|
||||
/// Configure WebDAV connection
|
||||
Future<bool> configure({
|
||||
required String baseUrl,
|
||||
required String username,
|
||||
String? password,
|
||||
String? deviceName,
|
||||
String? syncFolderName,
|
||||
}) async {
|
||||
try {
|
||||
// For updates without password, get existing password
|
||||
String actualPassword = password ?? '';
|
||||
if (password == null) {
|
||||
actualPassword = await _secureStorage.read(key: _passwordKey) ?? '';
|
||||
if (actualPassword.isEmpty) {
|
||||
throw Exception('No existing password found and no new password provided');
|
||||
}
|
||||
}
|
||||
|
||||
// Validate and normalize base URL
|
||||
final normalizedUrl = _normalizeUrl(baseUrl);
|
||||
|
||||
// Build the full WebDAV URL with username for Nextcloud/ownCloud
|
||||
final fullWebdavUrl = _buildFullWebDAVUrl(normalizedUrl, username);
|
||||
|
||||
// Test connection with smart fallback
|
||||
final testResult = await _testConnectionWithFallback(
|
||||
fullWebdavUrl,
|
||||
username,
|
||||
actualPassword,
|
||||
baseUrl, // Original URL for fallback attempts
|
||||
);
|
||||
|
||||
if (!testResult.success) {
|
||||
throw Exception(testResult.errorMessage);
|
||||
}
|
||||
|
||||
final finalUrl = testResult.workingUrl!;
|
||||
|
||||
// Save configuration with the working URL
|
||||
await _secureStorage.write(key: _baseUrlKey, value: finalUrl);
|
||||
await _secureStorage.write(key: _lastWorkingUrlKey, value: finalUrl);
|
||||
await _secureStorage.write(key: _usernameKey, value: username);
|
||||
await _secureStorage.write(key: _passwordKey, value: actualPassword);
|
||||
|
||||
if (deviceName != null && deviceName.isNotEmpty) {
|
||||
await _secureStorage.write(key: _deviceNameKey, value: deviceName);
|
||||
_currentDeviceName = deviceName;
|
||||
}
|
||||
|
||||
// Store sync folder name
|
||||
final folderName = syncFolderName ?? 'Supplements';
|
||||
await _secureStorage.write(key: _syncFolderNameKey, value: folderName);
|
||||
_syncFolderName = folderName;
|
||||
|
||||
// Initialize client with the working URL
|
||||
_webdavClient = newClient(
|
||||
finalUrl,
|
||||
user: username,
|
||||
password: actualPassword,
|
||||
debug: kDebugMode,
|
||||
);
|
||||
|
||||
// Ensure sync directory exists
|
||||
await _ensureSyncDirectoryExists();
|
||||
|
||||
if (kDebugMode) {
|
||||
print('WebDAV configured successfully: $finalUrl');
|
||||
print('Original URL: $baseUrl -> Detected: $finalUrl');
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('WebDAV configuration failed: $e');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove WebDAV configuration
|
||||
Future<void> clearConfiguration() async {
|
||||
await _secureStorage.delete(key: _baseUrlKey);
|
||||
await _secureStorage.delete(key: _usernameKey);
|
||||
await _secureStorage.delete(key: _passwordKey);
|
||||
await _secureStorage.delete(key: _deviceNameKey);
|
||||
await _secureStorage.delete(key: _lastSyncTimeKey);
|
||||
await _secureStorage.delete(key: _lastWorkingUrlKey);
|
||||
await _secureStorage.delete(key: _syncFolderNameKey);
|
||||
_webdavClient = null;
|
||||
_syncFolderName = null;
|
||||
}
|
||||
|
||||
/// Test WebDAV connection
|
||||
Future<bool> testConnection() async {
|
||||
try {
|
||||
await _ensureClient();
|
||||
if (_webdavClient == null) return false;
|
||||
|
||||
await _webdavClient!.ping();
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('WebDAV connection test failed: $e');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if device has internet connectivity
|
||||
Future<bool> hasConnectivity() async {
|
||||
final connectivityResult = await _connectivity.checkConnectivity();
|
||||
return connectivityResult.any((result) =>
|
||||
result == ConnectivityResult.mobile ||
|
||||
result == ConnectivityResult.wifi ||
|
||||
result == ConnectivityResult.ethernet);
|
||||
}
|
||||
|
||||
/// Perform full sync operation
|
||||
Future<SyncResult> performSync() async {
|
||||
final syncStartTime = DateTime.now();
|
||||
|
||||
try {
|
||||
// Check connectivity
|
||||
if (!await hasConnectivity()) {
|
||||
return SyncResult.failure(
|
||||
error: 'No internet connection',
|
||||
status: SyncOperationStatus.networkError,
|
||||
);
|
||||
}
|
||||
|
||||
// Ensure client is initialized
|
||||
await _ensureClient();
|
||||
if (_webdavClient == null) {
|
||||
return SyncResult.failure(
|
||||
error: 'WebDAV client not configured',
|
||||
status: SyncOperationStatus.authenticationError,
|
||||
);
|
||||
}
|
||||
|
||||
// Download remote data
|
||||
final remoteSyncData = await _downloadSyncData();
|
||||
|
||||
// Get local data that needs syncing
|
||||
final localSyncData = await _getLocalSyncData();
|
||||
|
||||
// Merge data and detect conflicts
|
||||
final mergeResult = await _mergeData(localSyncData, remoteSyncData);
|
||||
|
||||
// Upload merged data back to server
|
||||
if (mergeResult.hasChanges) {
|
||||
await _uploadSyncData(mergeResult.mergedData);
|
||||
}
|
||||
|
||||
// Update local sync status
|
||||
await _updateLocalSyncStatus(mergeResult.mergedData);
|
||||
|
||||
// Update last sync time
|
||||
await _updateLastSyncTime();
|
||||
|
||||
final syncDuration = DateTime.now().difference(syncStartTime);
|
||||
|
||||
return SyncResult.success(
|
||||
conflicts: mergeResult.conflicts,
|
||||
statistics: SyncStatistics(
|
||||
supplementsUploaded: mergeResult.statistics.supplementsUploaded,
|
||||
supplementsDownloaded: mergeResult.statistics.supplementsDownloaded,
|
||||
intakesUploaded: mergeResult.statistics.intakesUploaded,
|
||||
intakesDownloaded: mergeResult.statistics.intakesDownloaded,
|
||||
conflictsResolved: mergeResult.statistics.conflictsResolved,
|
||||
syncDuration: syncDuration,
|
||||
),
|
||||
);
|
||||
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('Sync operation failed: $e');
|
||||
}
|
||||
|
||||
SyncOperationStatus status = SyncOperationStatus.serverError;
|
||||
if (e is SocketException || e.toString().contains('network')) {
|
||||
status = SyncOperationStatus.networkError;
|
||||
} else if (e.toString().contains('401') || e.toString().contains('403')) {
|
||||
status = SyncOperationStatus.authenticationError;
|
||||
}
|
||||
|
||||
return SyncResult.failure(
|
||||
error: e.toString(),
|
||||
status: status,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Get last sync time
|
||||
Future<DateTime?> getLastSyncTime() async {
|
||||
final lastSyncStr = await _secureStorage.read(key: _lastSyncTimeKey);
|
||||
if (lastSyncStr != null) {
|
||||
return DateTime.tryParse(lastSyncStr);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get current device info
|
||||
Future<Map<String, String?>> getDeviceInfo() async {
|
||||
await _ensureDeviceInfo();
|
||||
return {
|
||||
'deviceId': _currentDeviceId,
|
||||
'deviceName': _currentDeviceName,
|
||||
};
|
||||
}
|
||||
|
||||
/// Get the last working WebDAV URL
|
||||
Future<String?> getLastWorkingUrl() async {
|
||||
return await _secureStorage.read(key: _lastWorkingUrlKey);
|
||||
}
|
||||
|
||||
/// Get stored server URL
|
||||
Future<String?> getServerUrl() async {
|
||||
return await _secureStorage.read(key: _baseUrlKey);
|
||||
}
|
||||
|
||||
/// Get stored username
|
||||
Future<String?> getUsername() async {
|
||||
return await _secureStorage.read(key: _usernameKey);
|
||||
}
|
||||
|
||||
/// Get stored sync folder name
|
||||
Future<String?> getSyncFolderName() async {
|
||||
final folderName = await _secureStorage.read(key: _syncFolderNameKey);
|
||||
return folderName ?? 'Supplements';
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
||||
Future<void> _ensureDeviceInfo() async {
|
||||
_currentDeviceId = await _secureStorage.read(key: _deviceIdKey);
|
||||
if (_currentDeviceId == null) {
|
||||
_currentDeviceId = _generateDeviceId();
|
||||
await _secureStorage.write(key: _deviceIdKey, value: _currentDeviceId!);
|
||||
}
|
||||
|
||||
_currentDeviceName = await _secureStorage.read(key: _deviceNameKey);
|
||||
if (_currentDeviceName == null) {
|
||||
_currentDeviceName = _getDefaultDeviceName();
|
||||
await _secureStorage.write(key: _deviceNameKey, value: _currentDeviceName!);
|
||||
}
|
||||
}
|
||||
|
||||
String _generateDeviceId() {
|
||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final random = DateTime.now().microsecond;
|
||||
return 'device_${timestamp}_$random';
|
||||
}
|
||||
|
||||
String _getDefaultDeviceName() {
|
||||
if (Platform.isAndroid) return 'Android Device';
|
||||
if (Platform.isIOS) return 'iOS Device';
|
||||
if (Platform.isWindows) return 'Windows PC';
|
||||
if (Platform.isMacOS) return 'Mac';
|
||||
if (Platform.isLinux) return 'Linux PC';
|
||||
return 'Unknown Device';
|
||||
}
|
||||
|
||||
String _normalizeUrl(String url) {
|
||||
// Clean and trim the URL
|
||||
url = url.trim();
|
||||
if (url.endsWith('/')) {
|
||||
url = url.substring(0, url.length - 1);
|
||||
}
|
||||
|
||||
// Add protocol if missing - try HTTPS first, fallback to HTTP if needed
|
||||
if (!url.startsWith('http://') && !url.startsWith('https://')) {
|
||||
url = 'https://$url';
|
||||
}
|
||||
|
||||
return _detectAndBuildWebDAVUrl(url);
|
||||
}
|
||||
|
||||
/// Advanced server detection and WebDAV URL building
|
||||
String _detectAndBuildWebDAVUrl(String baseUrl) {
|
||||
final uri = Uri.tryParse(baseUrl);
|
||||
if (uri == null) return baseUrl;
|
||||
|
||||
final host = uri.host.toLowerCase();
|
||||
final path = uri.path.toLowerCase();
|
||||
|
||||
// If already contains WebDAV path, return as-is
|
||||
if (path.contains('/remote.php/dav') || path.contains('/remote.php/webdav')) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
// Nextcloud detection patterns
|
||||
if (_isNextcloudServer(host, path)) {
|
||||
return _buildNextcloudUrl(baseUrl, uri);
|
||||
}
|
||||
|
||||
// ownCloud detection patterns
|
||||
if (_isOwnCloudServer(host, path)) {
|
||||
return _buildOwnCloudUrl(baseUrl, uri);
|
||||
}
|
||||
|
||||
// Generic WebDAV detection
|
||||
if (_isGenericWebDAVServer(host, path)) {
|
||||
return _buildGenericWebDAVUrl(baseUrl, uri);
|
||||
}
|
||||
|
||||
// Default: assume it's a base URL and try Nextcloud first (most common)
|
||||
return _buildNextcloudUrl(baseUrl, uri);
|
||||
}
|
||||
|
||||
/// Detect if server is likely Nextcloud
|
||||
bool _isNextcloudServer(String host, String path) {
|
||||
// Common Nextcloud hosting patterns
|
||||
final nextcloudPatterns = [
|
||||
'nextcloud',
|
||||
'cloud',
|
||||
'nc.',
|
||||
'.cloud.',
|
||||
'files.',
|
||||
'drive.',
|
||||
];
|
||||
|
||||
// Check hostname patterns
|
||||
for (final pattern in nextcloudPatterns) {
|
||||
if (host.contains(pattern)) return true;
|
||||
}
|
||||
|
||||
// Check path patterns
|
||||
if (path.contains('nextcloud') || path.contains('index.php/apps/files')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Detect if server is likely ownCloud
|
||||
bool _isOwnCloudServer(String host, String path) {
|
||||
final owncloudPatterns = [
|
||||
'owncloud',
|
||||
'oc.',
|
||||
'.owncloud.',
|
||||
];
|
||||
|
||||
// Check hostname patterns
|
||||
for (final pattern in owncloudPatterns) {
|
||||
if (host.contains(pattern)) return true;
|
||||
}
|
||||
|
||||
// Check path patterns
|
||||
if (path.contains('owncloud') || path.contains('index.php/apps/files')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Detect if server might be generic WebDAV
|
||||
bool _isGenericWebDAVServer(String host, String path) {
|
||||
final webdavPatterns = [
|
||||
'webdav',
|
||||
'dav',
|
||||
'caldav',
|
||||
'carddav',
|
||||
];
|
||||
|
||||
// Check hostname and path for WebDAV indicators
|
||||
for (final pattern in webdavPatterns) {
|
||||
if (host.contains(pattern) || path.contains(pattern)) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Build Nextcloud WebDAV URL with username detection
|
||||
String _buildNextcloudUrl(String baseUrl, Uri uri) {
|
||||
String webdavUrl = '${uri.scheme}://${uri.host}';
|
||||
|
||||
if (uri.hasPort && uri.port != 80 && uri.port != 443) {
|
||||
webdavUrl += ':${uri.port}';
|
||||
}
|
||||
|
||||
// Handle subdirectory installations
|
||||
String basePath = uri.path;
|
||||
if (basePath.isNotEmpty && basePath != '/') {
|
||||
// Remove common Nextcloud paths that shouldn't be in base
|
||||
basePath = basePath.replaceAll(RegExp(r'/index\.php.*$'), '');
|
||||
basePath = basePath.replaceAll(RegExp(r'/apps/files.*$'), '');
|
||||
webdavUrl += basePath;
|
||||
}
|
||||
|
||||
// Add Nextcloud WebDAV path - we'll need username later
|
||||
webdavUrl += '/remote.php/dav/files/';
|
||||
|
||||
return webdavUrl;
|
||||
}
|
||||
|
||||
/// Build ownCloud WebDAV URL
|
||||
String _buildOwnCloudUrl(String baseUrl, Uri uri) {
|
||||
String webdavUrl = '${uri.scheme}://${uri.host}';
|
||||
|
||||
if (uri.hasPort && uri.port != 80 && uri.port != 443) {
|
||||
webdavUrl += ':${uri.port}';
|
||||
}
|
||||
|
||||
// Handle subdirectory installations
|
||||
String basePath = uri.path;
|
||||
if (basePath.isNotEmpty && basePath != '/') {
|
||||
basePath = basePath.replaceAll(RegExp(r'/index\.php.*$'), '');
|
||||
basePath = basePath.replaceAll(RegExp(r'/apps/files.*$'), '');
|
||||
webdavUrl += basePath;
|
||||
}
|
||||
|
||||
webdavUrl += '/remote.php/webdav/';
|
||||
|
||||
return webdavUrl;
|
||||
}
|
||||
|
||||
/// Build generic WebDAV URL
|
||||
String _buildGenericWebDAVUrl(String baseUrl, Uri uri) {
|
||||
// For generic WebDAV, we assume the URL provided is correct
|
||||
// but we might need to add common WebDAV paths if missing
|
||||
if (!uri.path.endsWith('/')) {
|
||||
return '$baseUrl/';
|
||||
}
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
Future<void> _ensureClient() async {
|
||||
if (_webdavClient == null) {
|
||||
final baseUrl = await _secureStorage.read(key: _baseUrlKey);
|
||||
final username = await _secureStorage.read(key: _usernameKey);
|
||||
final password = await _secureStorage.read(key: _passwordKey);
|
||||
|
||||
if (baseUrl != null && username != null && password != null) {
|
||||
_webdavClient = newClient(
|
||||
baseUrl,
|
||||
user: username,
|
||||
password: password,
|
||||
debug: kDebugMode,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _ensureSyncDirectoryExists() async {
|
||||
if (_webdavClient == null) return;
|
||||
|
||||
// Get the configured folder name, default to 'Supplements'
|
||||
final folderName = _syncFolderName ?? await getSyncFolderName() ?? 'Supplements';
|
||||
|
||||
try {
|
||||
await _webdavClient!.mkdir(folderName);
|
||||
} catch (e) {
|
||||
// Directory might already exist, ignore error
|
||||
if (kDebugMode && !e.toString().contains('409')) {
|
||||
print('Failed to create sync directory ($folderName): $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<SyncData?> _downloadSyncData() async {
|
||||
if (_webdavClient == null) return null;
|
||||
|
||||
try {
|
||||
final folderName = _syncFolderName ?? await getSyncFolderName() ?? 'Supplements';
|
||||
final syncFilePath = '$folderName/${SyncConstants.syncFileName}';
|
||||
final fileData = await _webdavClient!.read(syncFilePath);
|
||||
final jsonString = utf8.decode(fileData);
|
||||
return SyncData.fromJsonString(jsonString);
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('Failed to download sync data: $e');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<SyncData> _getLocalSyncData() async {
|
||||
await _ensureDeviceInfo();
|
||||
|
||||
final supplements = await _databaseHelper.getAllSupplements();
|
||||
final archivedSupplements = await _databaseHelper.getArchivedSupplements();
|
||||
final allSupplements = [...supplements, ...archivedSupplements];
|
||||
|
||||
// Get all intakes (we'll need to implement a method to get all intakes)
|
||||
final intakes = await _getAllIntakes();
|
||||
|
||||
return SyncData(
|
||||
version: SyncConstants.currentSyncVersion,
|
||||
deviceId: _currentDeviceId!,
|
||||
deviceName: _currentDeviceName!,
|
||||
syncTimestamp: DateTime.now(),
|
||||
supplements: allSupplements,
|
||||
intakes: intakes,
|
||||
metadata: {
|
||||
'totalSupplements': allSupplements.length,
|
||||
'totalIntakes': intakes.length,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<SupplementIntake>> _getAllIntakes() async {
|
||||
// This is a simplified version - in practice, you might want to limit
|
||||
// to a certain date range or implement pagination for large datasets
|
||||
final now = DateTime.now();
|
||||
final oneYearAgo = now.subtract(const Duration(days: 365));
|
||||
|
||||
List<SupplementIntake> allIntakes = [];
|
||||
DateTime current = oneYearAgo;
|
||||
|
||||
while (current.isBefore(now)) {
|
||||
final monthIntakes = await _databaseHelper.getIntakesForMonth(
|
||||
current.year,
|
||||
current.month,
|
||||
);
|
||||
allIntakes.addAll(monthIntakes);
|
||||
current = DateTime(current.year, current.month + 1);
|
||||
}
|
||||
|
||||
return allIntakes;
|
||||
}
|
||||
|
||||
Future<_MergeResult> _mergeData(SyncData local, SyncData? remote) async {
|
||||
if (remote == null) {
|
||||
// No remote data, just mark local data as pending sync
|
||||
return _MergeResult(
|
||||
mergedData: local,
|
||||
conflicts: [],
|
||||
hasChanges: true,
|
||||
statistics: SyncStatistics(
|
||||
supplementsUploaded: local.supplements.length,
|
||||
intakesUploaded: local.intakes.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final conflicts = <SyncConflict>[];
|
||||
final mergedSupplements = <String, Supplement>{};
|
||||
final mergedIntakes = <String, SupplementIntake>{};
|
||||
|
||||
// Merge supplements
|
||||
for (final localSupplement in local.supplements) {
|
||||
mergedSupplements[localSupplement.syncId] = localSupplement;
|
||||
}
|
||||
|
||||
int supplementsDownloaded = 0;
|
||||
int supplementsUploaded = local.supplements.length;
|
||||
|
||||
for (final remoteSupplement in remote.supplements) {
|
||||
final localSupplement = mergedSupplements[remoteSupplement.syncId];
|
||||
|
||||
if (localSupplement == null) {
|
||||
// New remote supplement
|
||||
mergedSupplements[remoteSupplement.syncId] = remoteSupplement;
|
||||
supplementsDownloaded++;
|
||||
} else {
|
||||
// Check for conflicts
|
||||
if (localSupplement.lastModified.isAfter(remoteSupplement.lastModified)) {
|
||||
// Local is newer, keep local
|
||||
continue;
|
||||
} else if (remoteSupplement.lastModified.isAfter(localSupplement.lastModified)) {
|
||||
// Remote is newer, use remote
|
||||
mergedSupplements[remoteSupplement.syncId] = remoteSupplement;
|
||||
supplementsDownloaded++;
|
||||
} else {
|
||||
// Same timestamp - potential conflict if data differs
|
||||
if (!_supplementsEqual(localSupplement, remoteSupplement)) {
|
||||
conflicts.add(SyncConflict(
|
||||
syncId: localSupplement.syncId,
|
||||
type: ConflictType.modification,
|
||||
localTimestamp: localSupplement.lastModified,
|
||||
remoteTimestamp: remoteSupplement.lastModified,
|
||||
localData: localSupplement.toMap(),
|
||||
remoteData: remoteSupplement.toMap(),
|
||||
suggestedResolution: ConflictResolutionStrategy.preferNewer,
|
||||
));
|
||||
|
||||
// For now, keep local version
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge intakes (intakes are usually append-only, so fewer conflicts)
|
||||
for (final localIntake in local.intakes) {
|
||||
mergedIntakes[localIntake.syncId] = localIntake;
|
||||
}
|
||||
|
||||
int intakesDownloaded = 0;
|
||||
int intakesUploaded = local.intakes.length;
|
||||
|
||||
for (final remoteIntake in remote.intakes) {
|
||||
if (!mergedIntakes.containsKey(remoteIntake.syncId)) {
|
||||
mergedIntakes[remoteIntake.syncId] = remoteIntake;
|
||||
intakesDownloaded++;
|
||||
}
|
||||
}
|
||||
|
||||
final mergedData = SyncData(
|
||||
version: SyncConstants.currentSyncVersion,
|
||||
deviceId: local.deviceId,
|
||||
deviceName: local.deviceName,
|
||||
syncTimestamp: DateTime.now(),
|
||||
supplements: mergedSupplements.values.toList(),
|
||||
intakes: mergedIntakes.values.toList(),
|
||||
metadata: {
|
||||
'mergedAt': DateTime.now().toIso8601String(),
|
||||
'sourceDevices': [local.deviceId, remote.deviceId],
|
||||
'conflicts': conflicts.length,
|
||||
},
|
||||
);
|
||||
|
||||
return _MergeResult(
|
||||
mergedData: mergedData,
|
||||
conflicts: conflicts,
|
||||
hasChanges: supplementsDownloaded > 0 || intakesDownloaded > 0 || conflicts.isNotEmpty,
|
||||
statistics: SyncStatistics(
|
||||
supplementsUploaded: supplementsUploaded,
|
||||
supplementsDownloaded: supplementsDownloaded,
|
||||
intakesUploaded: intakesUploaded,
|
||||
intakesDownloaded: intakesDownloaded,
|
||||
conflictsResolved: 0, // Conflicts are not auto-resolved yet
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool _supplementsEqual(Supplement a, Supplement b) {
|
||||
return a.name == b.name &&
|
||||
a.brand == b.brand &&
|
||||
a.numberOfUnits == b.numberOfUnits &&
|
||||
a.unitType == b.unitType &&
|
||||
a.frequencyPerDay == b.frequencyPerDay &&
|
||||
a.reminderTimes.join(',') == b.reminderTimes.join(',') &&
|
||||
a.notes == b.notes &&
|
||||
a.isActive == b.isActive &&
|
||||
a.isDeleted == b.isDeleted &&
|
||||
_ingredientsEqual(a.ingredients, b.ingredients);
|
||||
}
|
||||
|
||||
bool _ingredientsEqual(List ingredients1, List ingredients2) {
|
||||
if (ingredients1.length != ingredients2.length) return false;
|
||||
|
||||
for (int i = 0; i < ingredients1.length; i++) {
|
||||
final ing1 = ingredients1[i];
|
||||
final ing2 = ingredients2[i];
|
||||
if (ing1.name != ing2.name ||
|
||||
ing1.amount != ing2.amount ||
|
||||
ing1.unit != ing2.unit) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _uploadSyncData(SyncData syncData) async {
|
||||
if (_webdavClient == null) return;
|
||||
|
||||
final folderName = _syncFolderName ?? await getSyncFolderName() ?? 'Supplements';
|
||||
final syncFilePath = '$folderName/${SyncConstants.syncFileName}';
|
||||
final jsonString = syncData.toJsonString();
|
||||
final jsonBytes = utf8.encode(jsonString);
|
||||
|
||||
// Create backup of existing file first
|
||||
try {
|
||||
final backupPath = '$folderName/${SyncConstants.syncFileBackupName}';
|
||||
final existingData = await _webdavClient!.read(syncFilePath);
|
||||
await _webdavClient!.write(backupPath, Uint8List.fromList(existingData));
|
||||
} catch (e) {
|
||||
// Backup failed, continue anyway
|
||||
if (kDebugMode) {
|
||||
print('Failed to create backup: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Upload new sync data
|
||||
await _webdavClient!.write(syncFilePath, jsonBytes);
|
||||
|
||||
if (kDebugMode) {
|
||||
print('Sync data uploaded successfully to $folderName');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _updateLocalSyncStatus(SyncData mergedData) async {
|
||||
// Mark all synced items as synced in local database
|
||||
for (final supplement in mergedData.supplements) {
|
||||
if (supplement.syncStatus != SyncStatus.synced) {
|
||||
await _databaseHelper.markSupplementAsSynced(supplement.syncId);
|
||||
}
|
||||
}
|
||||
|
||||
for (final intake in mergedData.intakes) {
|
||||
if (intake.syncStatus != SyncStatus.synced) {
|
||||
await _databaseHelper.markIntakeAsSynced(intake.syncId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _updateLastSyncTime() async {
|
||||
await _secureStorage.write(
|
||||
key: _lastSyncTimeKey,
|
||||
value: DateTime.now().toIso8601String(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Build full WebDAV URL including username for Nextcloud/ownCloud
|
||||
String _buildFullWebDAVUrl(String baseUrl, String username) {
|
||||
// If URL ends with /files/ (Nextcloud), add username
|
||||
if (baseUrl.endsWith('/remote.php/dav/files/')) {
|
||||
return '$baseUrl$username/';
|
||||
}
|
||||
|
||||
// If URL ends with /webdav/ (ownCloud), it's ready to use
|
||||
if (baseUrl.endsWith('/remote.php/webdav/')) {
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
// For other cases, return as-is
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
/// Test connection with smart fallback logic
|
||||
Future<_ConnectionTestResult> _testConnectionWithFallback(
|
||||
String primaryUrl,
|
||||
String username,
|
||||
String password,
|
||||
String originalUrl,
|
||||
) async {
|
||||
// Try the primary detected URL first
|
||||
try {
|
||||
final client = newClient(primaryUrl, user: username, password: password, debug: kDebugMode);
|
||||
await client.ping();
|
||||
return _ConnectionTestResult.success(primaryUrl);
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('Primary URL failed: $primaryUrl - $e');
|
||||
}
|
||||
}
|
||||
|
||||
// Generate fallback URLs to try
|
||||
final fallbackUrls = _generateFallbackUrls(originalUrl, username);
|
||||
|
||||
for (final fallbackUrl in fallbackUrls) {
|
||||
try {
|
||||
final client = newClient(fallbackUrl, user: username, password: password, debug: kDebugMode);
|
||||
await client.ping();
|
||||
|
||||
if (kDebugMode) {
|
||||
print('Fallback URL succeeded: $fallbackUrl');
|
||||
}
|
||||
|
||||
return _ConnectionTestResult.success(fallbackUrl);
|
||||
} catch (e) {
|
||||
if (kDebugMode) {
|
||||
print('Fallback URL failed: $fallbackUrl - $e');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return _ConnectionTestResult.failure('Could not connect to WebDAV server. Please check your server URL, username, and password.');
|
||||
}
|
||||
|
||||
/// Generate fallback URLs to try if primary detection fails
|
||||
List<String> _generateFallbackUrls(String originalUrl, String username) {
|
||||
final fallbackUrls = <String>[];
|
||||
|
||||
final uri = Uri.tryParse(originalUrl.startsWith('http') ? originalUrl : 'https://$originalUrl');
|
||||
if (uri == null) return fallbackUrls;
|
||||
|
||||
String baseUrl = '${uri.scheme}://${uri.host}';
|
||||
if (uri.hasPort && uri.port != 80 && uri.port != 443) {
|
||||
baseUrl += ':${uri.port}';
|
||||
}
|
||||
|
||||
// Add path if exists (for subdirectory installations)
|
||||
String installPath = uri.path;
|
||||
if (installPath.isNotEmpty && installPath != '/') {
|
||||
// Clean common paths
|
||||
installPath = installPath.replaceAll(RegExp(r'/index\.php.*$'), '');
|
||||
installPath = installPath.replaceAll(RegExp(r'/apps/files.*$'), '');
|
||||
installPath = installPath.replaceAll(RegExp(r'/remote\.php.*$'), '');
|
||||
baseUrl += installPath;
|
||||
}
|
||||
|
||||
// Try different combinations
|
||||
fallbackUrls.addAll([
|
||||
// Nextcloud variants
|
||||
'$baseUrl/remote.php/dav/files/$username/',
|
||||
'$baseUrl/nextcloud/remote.php/dav/files/$username/',
|
||||
'$baseUrl/cloud/remote.php/dav/files/$username/',
|
||||
|
||||
// ownCloud variants
|
||||
'$baseUrl/remote.php/webdav/',
|
||||
'$baseUrl/owncloud/remote.php/webdav/',
|
||||
|
||||
// Generic WebDAV variants
|
||||
'$baseUrl/webdav/',
|
||||
'$baseUrl/dav/',
|
||||
|
||||
// Try with different protocols if HTTPS failed
|
||||
..._generateProtocolVariants(baseUrl, username),
|
||||
]);
|
||||
|
||||
// Remove duplicates and return
|
||||
return fallbackUrls.toSet().toList();
|
||||
}
|
||||
|
||||
/// Generate protocol variants (HTTP/HTTPS)
|
||||
List<String> _generateProtocolVariants(String baseUrl, String username) {
|
||||
if (baseUrl.startsWith('https://')) {
|
||||
// Try HTTP variants
|
||||
final httpBase = baseUrl.replaceFirst('https://', 'http://');
|
||||
return [
|
||||
'$httpBase/remote.php/dav/files/$username/',
|
||||
'$httpBase/remote.php/webdav/',
|
||||
'$httpBase/webdav/',
|
||||
];
|
||||
} else if (baseUrl.startsWith('http://')) {
|
||||
// Try HTTPS variants
|
||||
final httpsBase = baseUrl.replaceFirst('http://', 'https://');
|
||||
return [
|
||||
'$httpsBase/remote.php/dav/files/$username/',
|
||||
'$httpsBase/remote.php/webdav/',
|
||||
'$httpsBase/webdav/',
|
||||
];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal class for merge operation results
|
||||
class _MergeResult {
|
||||
final SyncData mergedData;
|
||||
final List<SyncConflict> conflicts;
|
||||
final bool hasChanges;
|
||||
final SyncStatistics statistics;
|
||||
|
||||
const _MergeResult({
|
||||
required this.mergedData,
|
||||
required this.conflicts,
|
||||
required this.hasChanges,
|
||||
required this.statistics,
|
||||
});
|
||||
}
|
||||
|
||||
/// Internal class for connection test results
|
||||
class _ConnectionTestResult {
|
||||
final bool success;
|
||||
final String? workingUrl;
|
||||
final String? errorMessage;
|
||||
|
||||
const _ConnectionTestResult._({
|
||||
required this.success,
|
||||
this.workingUrl,
|
||||
this.errorMessage,
|
||||
});
|
||||
|
||||
factory _ConnectionTestResult.success(String url) {
|
||||
return _ConnectionTestResult._(success: true, workingUrl: url);
|
||||
}
|
||||
|
||||
factory _ConnectionTestResult.failure(String error) {
|
||||
return _ConnectionTestResult._(success: false, errorMessage: error);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user