todo-app/lib/attachments/image_store_io.dart
Krzysztof kuhy Rudnicki 9f2ffdb8a9
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Attach any file to a note, of any size, not only images
📎 now picks any file (Android: Camera / Gallery / File; desktop: an
unfiltered dialog) and the desktop page accepts any dropped file. Photo and
screenshot formats up to 64 MB are still re-encoded and shown inline;
everything else is stored byte for byte on dufs beside the images and linked
as [name](url), shown as a row with its size that opens in the platform's
app (Android) or a new browser tab (desktop). BACKLOG.md rewrites file links
to ~/data/cloud/todo-images/ like image links.

There is no size cap, so no layer holds a file in memory: uploads and
downloads stream through DufsImageClient, writes land in a .tmp renamed when
whole (an interrupted download no longer leaves a truncated file that looks
done), the desktop page POSTs the browser's own Blob with fetch, and Android's
"File" uses file_picker, because file_selector's Android side reads the whole
file into memory on the UI thread. Verified with a 1 GB file end to end on
desktop (peak RSS +36 MB) and on an API 36 emulator.

The wrapper serves attachments from the origin that holds the GitHub token
and the notes, so only script-free types open inline (nosniff), the rest
download; writes carrying another site's Origin are refused (this also
closes cross-site overwrites of the backup files); and attachment routes run
concurrently so a long upload or a playing video cannot stall the page.

Also: cupertino_icons 2.0.0 (unused, but the freshness gate blocks the
pubspec otherwise), open_file 4.0.0 and file_picker 13.1.0 pinned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 12:17:06 +02:00

140 lines
4.5 KiB
Dart

/// Android: attachments live in app storage and sync with dufs directly.
library;
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:todo/attachments/image_password_store.dart';
import 'package:todo/attachments/image_store_api.dart';
import 'package:todo/images/attachment_ingest.dart';
import 'package:todo/images/attachment_ref.dart';
import 'package:todo/images/dufs_image_client.dart';
import 'package:todo/images/image_cache_store.dart';
import 'package:todo/images/image_processing.dart';
/// Opens the store under the app-support directory's `images/`.
// coverage:ignore-start
// Platform wiring only: path_provider has no binding in unit tests, which
// construct [IoImageStore] over a temp directory instead.
Future<ImageStore> openImageStore() async {
final support = await getApplicationSupportDirectory();
final root = Directory(p.join(support.path, 'images'));
// Both pickers copy what they return into the cache directory.
final pickerCopies = (await getTemporaryDirectory()).path;
return IoImageStore(ImageCacheStore(root), pickerCopies: pickerCopies);
}
// coverage:ignore-end
/// [ImageStore] over a local [ImageCacheStore], uploading with the login
/// from [ImagePasswordStore].
class IoImageStore extends ImageStore {
/// Creates a store over [cache]. Picked files under [pickerCopies] are the
/// pickers' private copies and are moved rather than copied. The rest is
/// injectable for tests.
IoImageStore(
this.cache, {
this.pickerCopies,
this._passwords = const ImagePasswordStore(),
http.Client Function()? httpClient,
Future<Uint8List?> Function(Uint8List)? prepare,
}) : _httpClient = httpClient ?? http.Client.new,
_prepare = prepare ?? prepareImageInBackground,
_ingest = AttachmentIngest(
cache,
prepare: prepare ?? prepareImageInBackground,
);
/// The on-device attachments and upload queue.
final ImageCacheStore cache;
/// Directory the pickers copy their results into, if known.
final String? pickerCopies;
final ImagePasswordStore _passwords;
final http.Client Function() _httpClient;
final Future<Uint8List?> Function(Uint8List) _prepare;
final AttachmentIngest _ingest;
@override
Future<AttachmentRef?> attach(String noteId, Uint8List bytes) async {
final jpeg = await _prepare(bytes);
if (jpeg == null) return null;
final ref = AttachmentRef.create(noteId);
try {
await cache.put(ref, jpeg);
} on FileSystemException catch (e) {
throw ImageStoreException('Could not save the image: ${e.message}');
}
notifyListeners();
// Upload right away when online. An empty ref set never evicts, so this
// cannot race the link reaching the note.
unawaited(_sync(const {}));
return ref;
}
@override
Future<Attachment> attachFile(String noteId, XFile file) async {
final copies = pickerCopies;
final Attachment attachment;
try {
attachment = await _ingest.fromFile(
noteId,
file.name,
File(file.path),
move: copies != null && p.isWithin(copies, file.path),
);
} on FileSystemException catch (e) {
throw ImageStoreException('Could not save ${file.name}: ${e.message}');
}
notifyListeners();
unawaited(_sync(const {}));
return attachment;
}
@override
Future<void> reconcile(Iterable<String> noteTexts) =>
_sync(attachmentRefsAcross(noteTexts));
Future<void> _sync(Set<AttachmentRef> refs) async {
final login = await _passwords.login();
final client = login == null
? null
: DufsImageClient(login, httpClient: _httpClient());
try {
final report = await cache.reconcile(refs, client);
if (report.uploaded + report.downloaded + report.evicted > 0) {
notifyListeners();
}
} finally {
client?.close();
}
}
@override
ImageSource sourceFor(AttachmentRef ref) {
final file = cache.fileFor(ref);
return file.existsSync()
? LocalImageSource(file.path)
: const MissingImageSource();
}
@override
bool isPending(AttachmentRef ref) => cache.isPending(ref);
@override
Future<int?> sizeOf(AttachmentRef ref) async {
final file = cache.fileFor(ref);
return file.existsSync() ? await file.length() : null;
}
@override
Future<ImageStoreStatus> status() async => ImageStoreStatus(
configured: await _passwords.login() != null,
pending: cache.pending().length,
);
}