aves_mio1/lib/remote/run_remote_sync.dart
FabioMich66 084fa184da
Some checks failed
Quality check / Flutter analysis (push) Has been cancelled
Quality check / CodeQL analysis (java-kotlin) (push) Has been cancelled
ok con video e foto in galleria aves
2026-03-17 12:19:38 +01:00

60 lines
2.2 KiB
Dart

// lib/remote/run_remote_sync.dart
import 'package:aves/services/common/services.dart';
import 'package:aves/model/db/db.dart'; // LocalMediaDb
import 'package:aves/remote/remote_repository.dart';
import 'package:aves/remote/remote_models.dart'; // RemotePhotoItem
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:sqflite/sqflite.dart';
/// Esegue un giro di sync remoto riusando **la stessa connessione** del loader (4A).
/// Passa una funzione `fetch` che ritorna la lista di RemotePhotoItem da importare.
/// Ritorna il numero di elementi **nuovi/aggiornati** importati.
Future<int> runRemoteSyncOnceManaged({
required Future<List<RemotePhotoItem>> Function() fetch,
}) async {
try {
// 1) Usa la **stessa connessione** del loader
final localDb = getIt<LocalMediaDb>();
final db = localDb.rawDb;
final repo = RemoteRepository(db);
// 2) Conteggio pre (diagnostica)
final pre = (Sqflite.firstIntValue(
await db.rawQuery('SELECT COUNT(*) FROM entry WHERE origin=1')
) ?? 0);
debugPrint('[remote-sync][pre] count origin=1 = $pre');
// 3) Fetch dal server
final items = await fetch();
debugPrint('[remote-sync] fetchAll done, items=${items.length}');
if (items.isEmpty) {
debugPrint('[remote-sync] no items to import, exiting');
return 0;
}
// 4) Upsert + sanitize
final sw = Stopwatch()..start();
await repo.upsertAll(items);
await repo.sanitizeRemotes();
sw.stop();
debugPrint('[remote-sync] upsert+sanitize completed in ${sw.elapsedMilliseconds}ms');
// 5) Conteggio post e sample (diagnostica)
final post = (Sqflite.firstIntValue(
await db.rawQuery('SELECT COUNT(*) FROM entry WHERE origin=1')
) ?? 0);
debugPrint('[remote-sync][post] count origin=1 = $post');
final sample = await db.rawQuery(
'SELECT id, remoteId, provider, uri, trashed, dateModifiedMillis '
'FROM entry WHERE origin=1 ORDER BY id DESC LIMIT 3'
);
debugPrint('[remote-sync][post] sample origin=1 = $sample');
return (post - pre).clamp(0, items.length);
} catch (e, st) {
debugPrint('[remote-sync] ERROR: $e\n$st');
return 0;
}
}