// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:convert'; import 'dart:io'; /// Keeps server answers for reading offline, keyed by request path. abstract class ResponseCache { Future read(String key); Future write(String key, String body); /// Forgets everything (signing out, switching servers). Future clear(); } /// Kept in memory only: tests, and before the disk cache is ready. class MemoryCache implements ResponseCache { final _items = {}; @override Future read(String key) async => _items[key]; @override Future write(String key, String body) async => _items[key] = body; @override Future clear() async => _items.clear(); } /// One file per answer in the app's private storage. Pages someone opened /// stay readable without a connection; nothing is fetched ahead. class FileCache implements ResponseCache { FileCache(this.dir); final Directory dir; File _file(String key) => File( '${dir.path}/${base64Url.encode(utf8.encode(key)).replaceAll('=', '')}.json', ); @override Future read(String key) async { try { return await _file(key).readAsString(); } on FileSystemException { return null; } } @override Future write(String key, String body) async { try { await dir.create(recursive: true); // Write then rename, so a crash never leaves half a file. final tmp = File('${_file(key).path}.tmp'); await tmp.writeAsString(body, flush: true); await tmp.rename(_file(key).path); } on FileSystemException { // A full disk only costs offline reading. } } @override Future clear() async { if (await dir.exists()) await dir.delete(recursive: true); } }