feat(offline-first): persist hijri+unsplash cache and scale secondary times
This commit is contained in:
@@ -5,6 +5,7 @@ class HiveBoxes {
|
||||
HiveBoxes._();
|
||||
static const String settings = 'app_settings';
|
||||
static const String prayerSchedule = 'prayer_schedule';
|
||||
static const String hijriCache = 'hijri_cache';
|
||||
}
|
||||
|
||||
/// AppSettings stored in Hive.
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../../core/hijri_date.dart';
|
||||
import '../local/models.dart';
|
||||
|
||||
class HijriCalendarService {
|
||||
HijriCalendarService._({http.Client? client})
|
||||
@@ -11,35 +14,127 @@ class HijriCalendarService {
|
||||
|
||||
static final HijriCalendarService instance = HijriCalendarService._();
|
||||
static const String _baseUrl = 'https://api.myquran.com/v3/cal/hijr';
|
||||
static const Duration _requestTimeout = Duration(seconds: 5);
|
||||
static final RegExp _flexDateKeyRegex = RegExp(r'^(\d{4})-(\d{1,2})-(\d{1,2})$');
|
||||
|
||||
final http.Client _client;
|
||||
final Map<String, String> _cache = {};
|
||||
final DateFormat _dateFormat = DateFormat('yyyy-MM-dd');
|
||||
|
||||
DateTime _dateOnly(DateTime value) => DateTime(value.year, value.month, value.day);
|
||||
|
||||
String _dateKeyFromDate(DateTime value) => _dateFormat.format(_dateOnly(value));
|
||||
|
||||
String? _normalizeDateKey(String rawValue) {
|
||||
final trimmed = rawValue.trim();
|
||||
if (trimmed.isEmpty) return null;
|
||||
|
||||
final parsedIso = DateTime.tryParse(trimmed);
|
||||
if (parsedIso != null) return _dateKeyFromDate(parsedIso);
|
||||
|
||||
final match = _flexDateKeyRegex.firstMatch(trimmed);
|
||||
if (match == null) return null;
|
||||
final year = int.tryParse(match.group(1) ?? '');
|
||||
final month = int.tryParse(match.group(2) ?? '');
|
||||
final day = int.tryParse(match.group(3) ?? '');
|
||||
if (year == null || month == null || day == null) return null;
|
||||
if (month < 1 || month > 12 || day < 1 || day > 31) return null;
|
||||
return _dateKeyFromDate(DateTime(year, month, day));
|
||||
}
|
||||
|
||||
Box<String>? _diskCacheBoxOrNull() {
|
||||
if (!Hive.isBoxOpen(HiveBoxes.hijriCache)) return null;
|
||||
return Hive.box<String>(HiveBoxes.hijriCache);
|
||||
}
|
||||
|
||||
String? _readDiskCache(String dateKey) => _diskCacheBoxOrNull()?.get(dateKey);
|
||||
|
||||
Future<void> _writeDiskCache(String dateKey, String label) async {
|
||||
final box = _diskCacheBoxOrNull();
|
||||
if (box == null) return;
|
||||
await box.put(dateKey, label);
|
||||
}
|
||||
|
||||
Future<String?> _fetchHijriLabelFromApi(String dateKey) async {
|
||||
try {
|
||||
final response = await _client
|
||||
.get(Uri.parse('$_baseUrl/$dateKey'))
|
||||
.timeout(_requestTimeout);
|
||||
if (response.statusCode != 200) return null;
|
||||
|
||||
final payload = json.decode(response.body) as Map<String, dynamic>;
|
||||
return parseHijriLabel(payload);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> getHijriLabel(DateTime date) async {
|
||||
final dateOnly = DateTime(date.year, date.month, date.day);
|
||||
final dateKey = DateFormat('yyyy-MM-dd').format(dateOnly);
|
||||
final dateOnly = _dateOnly(date);
|
||||
final dateKey = _dateKeyFromDate(dateOnly);
|
||||
final cached = _cache[dateKey];
|
||||
if (cached != null) return cached;
|
||||
|
||||
try {
|
||||
final response = await _client.get(Uri.parse('$_baseUrl/$dateKey'));
|
||||
if (response.statusCode == 200) {
|
||||
final payload = json.decode(response.body) as Map<String, dynamic>;
|
||||
final label = parseHijriLabel(payload);
|
||||
if (label != null) {
|
||||
_cache[dateKey] = label;
|
||||
return label;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// Keep UI usable when the device is offline.
|
||||
final diskCached = _readDiskCache(dateKey);
|
||||
if (diskCached != null && diskCached.trim().isNotEmpty) {
|
||||
_cache[dateKey] = diskCached;
|
||||
return diskCached;
|
||||
}
|
||||
|
||||
final label = await _fetchHijriLabelFromApi(dateKey);
|
||||
if (label != null && label.trim().isNotEmpty) {
|
||||
_cache[dateKey] = label;
|
||||
await _writeDiskCache(dateKey, label);
|
||||
return label;
|
||||
}
|
||||
|
||||
// Keep UI usable when the device is offline.
|
||||
final fallback = HijriDateFormatter.format(dateOnly);
|
||||
_cache[dateKey] = fallback;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
/// Prefetch and persist Hijri labels for a set of Gregorian date keys.
|
||||
/// Date keys should be in `yyyy-MM-dd`, but this method normalizes inputs.
|
||||
Future<void> warmCacheForDateKeys(
|
||||
Iterable<String> rawDateKeys, {
|
||||
int maxConcurrentRequests = 4,
|
||||
}) async {
|
||||
final uniqueKeys = <String>{};
|
||||
for (final rawKey in rawDateKeys) {
|
||||
final normalized = _normalizeDateKey(rawKey);
|
||||
if (normalized != null) uniqueKeys.add(normalized);
|
||||
}
|
||||
if (uniqueKeys.isEmpty) return;
|
||||
|
||||
final pendingKeys = <String>[];
|
||||
for (final dateKey in uniqueKeys) {
|
||||
final memory = _cache[dateKey];
|
||||
if (memory != null && memory.trim().isNotEmpty) continue;
|
||||
|
||||
final disk = _readDiskCache(dateKey);
|
||||
if (disk != null && disk.trim().isNotEmpty) {
|
||||
_cache[dateKey] = disk;
|
||||
continue;
|
||||
}
|
||||
|
||||
pendingKeys.add(dateKey);
|
||||
}
|
||||
if (pendingKeys.isEmpty) return;
|
||||
|
||||
final concurrency = maxConcurrentRequests.clamp(1, 8);
|
||||
for (var index = 0; index < pendingKeys.length; index += concurrency) {
|
||||
final end = min(index + concurrency, pendingKeys.length);
|
||||
final chunk = pendingKeys.sublist(index, end);
|
||||
await Future.wait(chunk.map((dateKey) async {
|
||||
final label = await _fetchHijriLabelFromApi(dateKey);
|
||||
if (label == null || label.trim().isEmpty) return;
|
||||
_cache[dateKey] = label;
|
||||
await _writeDiskCache(dateKey, label);
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
static String? parseHijriLabel(Map<String, dynamic> payload) {
|
||||
if (payload['status'] != true) return null;
|
||||
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
import '../local/models.dart';
|
||||
import 'hijri_service.dart';
|
||||
import 'myquran_service.dart';
|
||||
|
||||
class ScheduleCacheStatus {
|
||||
@@ -196,6 +199,71 @@ class SyncService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pruneHijriCache(DateTime referenceDate) async {
|
||||
if (!Hive.isBoxOpen(HiveBoxes.hijriCache)) return;
|
||||
final hijriBox = Hive.box<String>(HiveBoxes.hijriCache);
|
||||
final staleKeys = staleScheduleKeys(
|
||||
hijriBox.keys.cast<String>(),
|
||||
referenceDate,
|
||||
);
|
||||
if (staleKeys.isNotEmpty) {
|
||||
await hijriBox.deleteAll(staleKeys);
|
||||
await hijriBox.compact();
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> _priorityHijriWarmupKeys(
|
||||
Set<String> allDateKeys,
|
||||
DateTime referenceDate,
|
||||
) {
|
||||
final prioritized = <String>{};
|
||||
for (var offset = 0; offset <= 7; offset++) {
|
||||
final key = _canonicalDateKey(referenceDate.add(Duration(days: offset)));
|
||||
if (allDateKeys.contains(key)) prioritized.add(key);
|
||||
}
|
||||
return prioritized;
|
||||
}
|
||||
|
||||
Set<String> _collectRollingWindowScheduleDateKeys(
|
||||
Box<DailyPrayerSchedule> scheduleBox,
|
||||
DateTime referenceDate,
|
||||
) {
|
||||
final allowedMonths = rollingWindowMonths(referenceDate);
|
||||
final keys = <String>{};
|
||||
|
||||
for (final rawKey in scheduleBox.keys) {
|
||||
if (rawKey is! String) continue;
|
||||
final parsed = _parseScheduleDate(rawKey);
|
||||
if (parsed == null) continue;
|
||||
final monthKey = DateFormat('yyyy-MM').format(parsed);
|
||||
if (!allowedMonths.contains(monthKey)) continue;
|
||||
keys.add(_canonicalDateKey(parsed));
|
||||
}
|
||||
|
||||
return keys;
|
||||
}
|
||||
|
||||
Future<void> _warmHijriCacheForScheduleRange(
|
||||
Box<DailyPrayerSchedule> scheduleBox,
|
||||
DateTime referenceDate,
|
||||
) async {
|
||||
final scheduleDateKeys = _collectRollingWindowScheduleDateKeys(
|
||||
scheduleBox,
|
||||
referenceDate,
|
||||
);
|
||||
if (scheduleDateKeys.isEmpty) return;
|
||||
|
||||
final priorityKeys = _priorityHijriWarmupKeys(scheduleDateKeys, referenceDate);
|
||||
if (priorityKeys.isNotEmpty) {
|
||||
await HijriCalendarService.instance.warmCacheForDateKeys(priorityKeys);
|
||||
}
|
||||
|
||||
final remainingKeys = scheduleDateKeys.difference(priorityKeys);
|
||||
if (remainingKeys.isNotEmpty) {
|
||||
unawaited(HijriCalendarService.instance.warmCacheForDateKeys(remainingKeys));
|
||||
}
|
||||
}
|
||||
|
||||
bool _shouldAttemptAutoRefresh({
|
||||
required ScheduleCacheStatus status,
|
||||
required bool hasTodayData,
|
||||
@@ -288,9 +356,11 @@ class SyncService {
|
||||
if (success) {
|
||||
if (hasCurrentMonth && hasNextMonth) {
|
||||
await _pruneScheduleCache(scheduleBox, now);
|
||||
await _pruneHijriCache(now);
|
||||
}
|
||||
settings.lastSyncDate = DateFormat('yyyy-MM-dd HH:mm').format(now);
|
||||
await settings.save();
|
||||
await _warmHijriCacheForScheduleRange(scheduleBox, now);
|
||||
}
|
||||
|
||||
return success;
|
||||
@@ -306,16 +376,20 @@ class SyncService {
|
||||
}
|
||||
|
||||
final now = referenceDate ?? DateTime.now();
|
||||
final scheduleBox =
|
||||
Hive.box<DailyPrayerSchedule>(HiveBoxes.prayerSchedule);
|
||||
final status = getCacheStatus(now);
|
||||
final hasTodayData = getTodaySchedule(now) != null;
|
||||
|
||||
if (!_shouldAttemptAutoRefresh(status: status, hasTodayData: hasTodayData)) {
|
||||
unawaited(_warmHijriCacheForScheduleRange(scheduleBox, now));
|
||||
return const AutoRefreshResult.skipped('cache-fresh');
|
||||
}
|
||||
|
||||
final lastAttempt = _parseAttemptTimestamp(settings.lastAutoSyncAttemptDate);
|
||||
if (lastAttempt != null &&
|
||||
now.difference(lastAttempt) < _autoRefreshCooldown) {
|
||||
unawaited(_warmHijriCacheForScheduleRange(scheduleBox, now));
|
||||
return const AutoRefreshResult.skipped('cooldown');
|
||||
}
|
||||
|
||||
@@ -323,6 +397,9 @@ class SyncService {
|
||||
await settings.save();
|
||||
|
||||
final synced = await syncMonthlyData(referenceDate: now);
|
||||
if (!synced) {
|
||||
unawaited(_warmHijriCacheForScheduleRange(scheduleBox, now));
|
||||
}
|
||||
return synced
|
||||
? const AutoRefreshResult.synced()
|
||||
: const AutoRefreshResult.failed('sync-failed');
|
||||
|
||||
131
lib/data/services/unsplash_cache_service.dart
Normal file
131
lib/data/services/unsplash_cache_service.dart
Normal file
@@ -0,0 +1,131 @@
|
||||
import 'dart:math';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
|
||||
import 'unsplash_service.dart';
|
||||
|
||||
/// Persistent Unsplash cache.
|
||||
/// Stores downloaded images by keyword so background can still render offline.
|
||||
class UnsplashCacheService {
|
||||
UnsplashCacheService._();
|
||||
static final UnsplashCacheService instance = UnsplashCacheService._();
|
||||
|
||||
static const int _maxCachedImagesPerKeyword = 24;
|
||||
static const Duration _requestTimeout = Duration(seconds: 10);
|
||||
|
||||
final Random _random = Random();
|
||||
|
||||
String _normalizeKeyword(String keyword) {
|
||||
final normalized = keyword.trim().toLowerCase().replaceAll(RegExp(r'\s+'), '_');
|
||||
final safe = normalized.replaceAll(RegExp(r'[^a-z0-9_\-]'), '');
|
||||
return safe.isEmpty ? 'mosque' : safe;
|
||||
}
|
||||
|
||||
Future<Directory> _cacheRootDirectory() async {
|
||||
final baseDir = await getApplicationSupportDirectory();
|
||||
final cacheDir = Directory('${baseDir.path}/unsplash_cache');
|
||||
if (!cacheDir.existsSync()) {
|
||||
await cacheDir.create(recursive: true);
|
||||
}
|
||||
return cacheDir;
|
||||
}
|
||||
|
||||
Future<Directory> _keywordDirectory(String keyword) async {
|
||||
final root = await _cacheRootDirectory();
|
||||
final folderName = _normalizeKeyword(keyword);
|
||||
final dir = Directory('${root.path}/$folderName');
|
||||
if (!dir.existsSync()) {
|
||||
await dir.create(recursive: true);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
String _filenameForUrl(String url) {
|
||||
final digest = sha1.convert(utf8.encode(url)).toString();
|
||||
return '$digest.jpg';
|
||||
}
|
||||
|
||||
Future<List<File>> _listCachedFiles(String keyword) async {
|
||||
final dir = await _keywordDirectory(keyword);
|
||||
final entities = await dir.list().toList();
|
||||
final files = entities.whereType<File>().where((file) {
|
||||
final ext = file.path.split('.').last.toLowerCase();
|
||||
return ext == 'jpg' || ext == 'jpeg' || ext == 'png' || ext == 'webp';
|
||||
}).toList();
|
||||
|
||||
files.sort((a, b) {
|
||||
final aTime = a.statSync().modified;
|
||||
final bTime = b.statSync().modified;
|
||||
return bTime.compareTo(aTime);
|
||||
});
|
||||
return files;
|
||||
}
|
||||
|
||||
Future<void> _pruneKeywordCache(String keyword) async {
|
||||
final files = await _listCachedFiles(keyword);
|
||||
if (files.length <= _maxCachedImagesPerKeyword) return;
|
||||
|
||||
for (final file in files.skip(_maxCachedImagesPerKeyword)) {
|
||||
try {
|
||||
if (file.existsSync()) {
|
||||
await file.delete();
|
||||
}
|
||||
} catch (_) {
|
||||
// Keep best effort only.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _downloadImage(String url, Directory destinationDir) async {
|
||||
try {
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri == null) return null;
|
||||
|
||||
final response = await http.get(uri).timeout(_requestTimeout);
|
||||
if (response.statusCode != 200 || response.bodyBytes.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final file = File('${destinationDir.path}/${_filenameForUrl(url)}');
|
||||
await file.writeAsBytes(response.bodyBytes, flush: true);
|
||||
return file.path;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns local cached image paths for the given keyword.
|
||||
Future<List<String>> getCachedImagePaths(String keyword) async {
|
||||
final files = await _listCachedFiles(keyword);
|
||||
return files.map((file) => file.path).toList(growable: false);
|
||||
}
|
||||
|
||||
/// Fetches fresh Unsplash URLs and persists them as local files.
|
||||
/// If fetch fails (offline), returns existing local cache.
|
||||
Future<List<String>> refreshKeywordCache(
|
||||
String keyword, {
|
||||
int downloadCount = 12,
|
||||
}) async {
|
||||
final urls = await UnsplashService.instance.fetchLandscapeBackgrounds(keyword);
|
||||
if (urls.isEmpty) {
|
||||
return getCachedImagePaths(keyword);
|
||||
}
|
||||
|
||||
final dir = await _keywordDirectory(keyword);
|
||||
final shuffled = List<String>.from(urls)..shuffle(_random);
|
||||
final targetCount = downloadCount.clamp(1, urls.length);
|
||||
|
||||
for (final url in shuffled.take(targetCount)) {
|
||||
final path = '${dir.path}/${_filenameForUrl(url)}';
|
||||
if (File(path).existsSync()) continue;
|
||||
await _downloadImage(url, dir);
|
||||
}
|
||||
|
||||
await _pruneKeywordCache(keyword);
|
||||
return getCachedImagePaths(keyword);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user