diff --git a/.claude/private/CLAUDE.md b/.claude/private/CLAUDE.md index ef4fe01..d93ca30 100644 Binary files a/.claude/private/CLAUDE.md and b/.claude/private/CLAUDE.md differ diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 27e57d7..c4cdb88 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,7 +72,7 @@ jobs: hook=packages/blob_storage_media_adapters/hook/build.dart version=$(sed -n "s/^const opusVersion = '\(.*\)';/\1/p" "$hook") pinned=$(grep -A1 '^const opusSha256' "$hook" | grep -o '[0-9a-f]\{64\}') - published=$(curl -fsSL https://downloads.xiph.org/releases/opus/SHA256SUMS.txt \ + published=$(curl -fsSL --retry 5 --retry-all-errors --retry-delay 10 https://downloads.xiph.org/releases/opus/SHA256SUMS.txt \ | grep " opus-$version.tar.gz$" | cut -d' ' -f1) echo "opus $version pinned=$pinned published=$published" test -n "$published" && test "$pinned" = "$published" diff --git a/apps/modusnote/android/app/src/main/AndroidManifest.xml b/apps/modusnote/android/app/src/main/AndroidManifest.xml index 25fb8b7..07af471 100644 --- a/apps/modusnote/android/app/src/main/AndroidManifest.xml +++ b/apps/modusnote/android/app/src/main/AndroidManifest.xml @@ -85,5 +85,9 @@ + + + + diff --git a/apps/modusnote/ios/Runner/Info.plist b/apps/modusnote/ios/Runner/Info.plist index 7f8639c..f23b359 100644 --- a/apps/modusnote/ios/Runner/Info.plist +++ b/apps/modusnote/ios/Runner/Info.plist @@ -5,9 +5,9 @@ NSMicrophoneUsageDescription Modus Notes records audio notes, song sketches and dream logs. Recordings are encrypted on this device before they are saved. NSPhotoLibraryUsageDescription - Modus Notes adds the pictures you choose to your pages. Each picture is encrypted on this device before it is saved. + Modus Notes adds the pictures and the short videos you choose to your pages. Each one is encrypted on this device before it is saved. NSCameraUsageDescription - Modus Notes does not use the camera; pictures are chosen from your photos. + Modus Notes uses the camera only when you record a short video for a step of a recipe. The video is cleaned of its location and encrypted on this device before it is saved. CADisableMinimumFrameDurationOnPhone CFBundleDevelopmentRegion diff --git a/apps/modusnote/lib/attachments/note_images.dart b/apps/modusnote/lib/attachments/note_images.dart index 81c0503..e8d3534 100644 --- a/apps/modusnote/lib/attachments/note_images.dart +++ b/apps/modusnote/lib/attachments/note_images.dart @@ -14,7 +14,16 @@ abstract interface class ImageChooser { Future choose(); } -/// The pictures of the vault's notes: picked from the device straight into +/// Port: lets the person pick or record one short video, as bytes. Null +/// when they cancel. Like [ImageChooser], no copy of its own is left. +abstract interface class VideoChooser { + /// From the camera when [camera], else from the device's videos. Throws + /// [VideoTooLargeException] for a file past [VideoProbe.maxBytes], + /// before reading it. + Future choose({required bool camera}); +} + +/// The pictures of the vault's notes, and the videos of recipes' steps: picked from the device straight into /// blobs sealed under the current GroupKey, and opened again in memory, /// downloaded first when another device added them. final class NoteImages { @@ -22,10 +31,12 @@ final class NoteImages { required this.blobs, required this._engine, required this._chooser, + this._videoChooser, this._ensureLocal, this._clock = DateTime.now, Random? random, }) : _images = ImageStorage(storage: blobs), + _videos = VideoStorage(storage: blobs), _random = random ?? Random.secure(); /// Where pictures land, beside the recordings. @@ -33,6 +44,11 @@ final class NoteImages { final ImageStorage _images; final SyncEngine _engine; final ImageChooser _chooser; + final VideoStorage _videos; + final VideoChooser? _videoChooser; + + /// Whether videos can be added here; off where nothing picks them. + bool get takesVideos => _videoChooser != null; final Future Function(SealedBlob blob)? _ensureLocal; final DateTime Function() _clock; final Random _random; @@ -70,6 +86,35 @@ final class NoteImages { ); } + /// A video the person picks or records, cleaned of its metadata and + /// sealed; null when they cancel. Throws [UnsupportedVideoException] or + /// [VideoTooLargeException] for a file this app does not keep. + Future chooseVideo({required bool camera}) async { + final bytes = await _videoChooser?.choose(camera: camera); + if (bytes == null) return null; + try { + final epoch = _engine.currentEpoch; + final metadata = await _videos.seal( + bytes, + id: _newBlobId(), + contentKey: _engine.contentKeyFor(epoch), + at: _clock(), + ); + return KeyedVideo(epoch: epoch, metadata: metadata); + } finally { + bytes.fillRange(0, bytes.length, 0); + } + } + + /// The video's bytes, checked against its metadata; errors as [open]. + Future openVideo(KeyedVideo video) async { + await _ensureLocal?.call(video.blob); + return _videos.open( + video.metadata, + contentKey: _engine.contentKeyFor(video.epoch), + ); + } + /// Opaque and random, like note ids: blob ids reach R2 in clear. BlobId _newBlobId() => BlobId( List.generate( diff --git a/apps/modusnote/lib/attachments/playable_video.dart b/apps/modusnote/lib/attachments/playable_video.dart new file mode 100644 index 0000000..62276c7 --- /dev/null +++ b/apps/modusnote/lib/attachments/playable_video.dart @@ -0,0 +1,12 @@ +/// A decrypted video handed to the platform's player, and taken back. +/// +/// The players of Android and iOS read only files or the network: on a +/// phone the clip is written to a file of its own in the app's private +/// cache, overwritten and deleted when the player closes, and the folder +/// is emptied when the vault opens, in case the app was stopped while one +/// played. In a browser it stays in memory, behind an object URL revoked +/// on close. +library; + +export 'playable_video_io.dart' + if (dart.library.js_interop) 'playable_video_web.dart'; diff --git a/apps/modusnote/lib/attachments/playable_video_io.dart b/apps/modusnote/lib/attachments/playable_video_io.dart new file mode 100644 index 0000000..387eea3 --- /dev/null +++ b/apps/modusnote/lib/attachments/playable_video_io.dart @@ -0,0 +1,53 @@ +import 'dart:io'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:path_provider/path_provider.dart'; +import 'package:video_player/video_player.dart'; + +/// [bytes] ready to play. [PlayableVideo.release] must be called once the +/// player closes. +Future playableVideo(Uint8List bytes) async { + final folder = await _folder(); + await folder.create(recursive: true); + final random = Random.secure(); + final name = List.generate( + 16, + (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ).join(); + final file = File('${folder.path}${Platform.pathSeparator}$name.mp4'); + await file.writeAsBytes(bytes, flush: true); + return PlayableVideo._(VideoPlayerController.file(file), file); +} + +/// Deletes what a player stopped before closing left behind. +Future sweepPlayableVideos() async { + try { + final folder = await _folder(); + if (await folder.exists()) await folder.delete(recursive: true); + } on FileSystemException { + // Nothing to sweep, or it goes next time. + } +} + +Future _folder() async => Directory( + '${(await getTemporaryDirectory()).path}${Platform.pathSeparator}videos', +); + +final class PlayableVideo { + PlayableVideo._(this.controller, this._file); + + final VideoPlayerController controller; + final File _file; + + Future release() async { + await controller.dispose(); + try { + final length = await _file.length(); + await _file.writeAsBytes(Uint8List(length), flush: true); + await _file.delete(); + } on FileSystemException { + // Already gone; the next sweep checks. + } + } +} diff --git a/apps/modusnote/lib/attachments/playable_video_web.dart b/apps/modusnote/lib/attachments/playable_video_web.dart new file mode 100644 index 0000000..67b9302 --- /dev/null +++ b/apps/modusnote/lib/attachments/playable_video_web.dart @@ -0,0 +1,31 @@ +import 'dart:js_interop'; +import 'dart:typed_data'; + +import 'package:video_player/video_player.dart'; +import 'package:web/web.dart' as web; + +/// [bytes] ready to play, from memory. [PlayableVideo.release] must be +/// called once the player closes. +Future playableVideo(Uint8List bytes) async { + final blob = web.Blob( + [bytes.toJS].toJS, + web.BlobPropertyBag(type: 'video/mp4'), + ); + final url = web.URL.createObjectURL(blob); + return PlayableVideo._(VideoPlayerController.networkUrl(Uri.parse(url)), url); +} + +/// Nothing is written to disk in a browser. +Future sweepPlayableVideos() async {} + +final class PlayableVideo { + PlayableVideo._(this.controller, this._url); + + final VideoPlayerController controller; + final String _url; + + Future release() async { + await controller.dispose(); + web.URL.revokeObjectURL(_url); + } +} diff --git a/apps/modusnote/lib/bootstrap/browser_image_chooser.dart b/apps/modusnote/lib/bootstrap/browser_image_chooser.dart index e9d38ad..c9f06dd 100644 --- a/apps/modusnote/lib/bootstrap/browser_image_chooser.dart +++ b/apps/modusnote/lib/bootstrap/browser_image_chooser.dart @@ -11,31 +11,48 @@ import '../attachments/note_images.dart'; /// no object URL, no request, nothing stored by the browser. final class BrowserImageChooser implements ImageChooser { @override - Future choose() async { - final input = web.HTMLInputElement() - ..type = 'file' - ..accept = [for (final f in ImageFormat.values) f.mimeType].join(','); - final picked = Completer(); - input - ..addEventListener( - 'change', - ((web.Event _) { - if (!picked.isCompleted) picked.complete(input.files?.item(0)); - }).toJS, - ) - ..addEventListener( - 'cancel', - ((web.Event _) { - if (!picked.isCompleted) picked.complete(null); - }).toJS, - ) - ..click(); - final file = await picked.future; - if (file == null) return null; - if (file.size > ImageProbe.maxBytes) throw const ImageTooLargeException(); - final buffer = await file.arrayBuffer().toDart; - // A copy in Dart's own memory: under WebAssembly the browser's buffer - // would otherwise be read through JS on every access. - return Uint8List.fromList(buffer.toDart.asUint8List()); + Future choose() => _pick( + [for (final f in ImageFormat.values) f.mimeType].join(','), + ImageProbe.maxBytes, + ); +} + +/// A video file, the same way; the browser has no camera of its own here. +final class BrowserVideoChooser implements VideoChooser { + @override + Future choose({required bool camera}) => + _pick('video/mp4,video/quicktime', VideoProbe.maxBytes, video: true); +} + +/// One file the person picks, read into memory; null when they cancel. +Future _pick(String accept, int max, {bool video = false}) async { + final input = web.HTMLInputElement() + ..type = 'file' + ..accept = accept; + final picked = Completer(); + input + ..addEventListener( + 'change', + ((web.Event _) { + if (!picked.isCompleted) picked.complete(input.files?.item(0)); + }).toJS, + ) + ..addEventListener( + 'cancel', + ((web.Event _) { + if (!picked.isCompleted) picked.complete(null); + }).toJS, + ) + ..click(); + final file = await picked.future; + if (file == null) return null; + if (file.size > max) { + throw video + ? const VideoTooLargeException() + : const ImageTooLargeException(); } + final buffer = await file.arrayBuffer().toDart; + // A copy in Dart's own memory: under WebAssembly the browser's buffer + // would otherwise be read through JS on every access. + return Uint8List.fromList(buffer.toDart.asUint8List()); } diff --git a/apps/modusnote/lib/bootstrap/gallery_image_chooser.dart b/apps/modusnote/lib/bootstrap/gallery_image_chooser.dart index 923b1fa..179116b 100644 --- a/apps/modusnote/lib/bootstrap/gallery_image_chooser.dart +++ b/apps/modusnote/lib/bootstrap/gallery_image_chooser.dart @@ -43,3 +43,27 @@ final class GalleryImageChooser implements ImageChooser { } } } + +/// Picks a video from the phone's library, or records one with the camera +/// (asked for at most a minute), with the system's own screens. Like +/// [GalleryImageChooser], the cache copy is read and deleted. +final class GalleryVideoChooser implements VideoChooser { + final _picker = ImagePicker(); + + @override + Future choose({required bool camera}) async { + final file = await _picker.pickVideo( + source: camera ? ImageSource.camera : ImageSource.gallery, + maxDuration: const Duration(seconds: 60), + ); + if (file == null) return null; + try { + if (await file.length() > VideoProbe.maxBytes) { + throw const VideoTooLargeException(); + } + return await file.readAsBytes(); + } finally { + await GalleryImageChooser._deleteCopy(file.path); + } + } +} diff --git a/apps/modusnote/lib/bootstrap/home_native.dart b/apps/modusnote/lib/bootstrap/home_native.dart index 9d35ffd..d1e0a0f 100644 --- a/apps/modusnote/lib/bootstrap/home_native.dart +++ b/apps/modusnote/lib/bootstrap/home_native.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:io'; import 'dart:ui' show PlatformDispatcher; @@ -17,6 +18,7 @@ import 'package:sodium/sodium_sumo.dart'; import 'package:sqlite3/sqlite3.dart'; import '../attachments/note_images.dart'; +import '../attachments/playable_video.dart'; import '../audio/note_playback.dart'; import '../audio/note_recorder.dart'; import '../sync/sync_config.dart'; @@ -163,12 +165,17 @@ VaultGate _gate({ blobs: blobs, engine: engine, ), - imagesFor: (engine, ensureLocal) => NoteImages( - blobs: blobs, - engine: engine, - chooser: GalleryImageChooser(), - ensureLocal: ensureLocal, - ), + imagesFor: (engine, ensureLocal) { + // A vault opening: what a player stopped too soon left goes. + unawaited(sweepPlayableVideos()); + return NoteImages( + blobs: blobs, + engine: engine, + chooser: GalleryImageChooser(), + videoChooser: GalleryVideoChooser(), + ensureLocal: ensureLocal, + ); + }, playbackFor: (engine, ensureLocal) => NotePlayback( decoding: RecordingPlayback( storage: blobs, diff --git a/apps/modusnote/lib/bootstrap/home_web.dart b/apps/modusnote/lib/bootstrap/home_web.dart index 079a30d..565e620 100644 --- a/apps/modusnote/lib/bootstrap/home_web.dart +++ b/apps/modusnote/lib/bootstrap/home_web.dart @@ -159,6 +159,7 @@ VaultGate _gate({ blobs: blobs, engine: engine, chooser: BrowserImageChooser(), + videoChooser: BrowserVideoChooser(), ensureLocal: ensureLocal, ), playbackFor: (engine, ensureLocal) => NotePlayback( diff --git a/apps/modusnote/lib/l10n/app_en.arb b/apps/modusnote/lib/l10n/app_en.arb index 1a68944..1e168cd 100644 --- a/apps/modusnote/lib/l10n/app_en.arb +++ b/apps/modusnote/lib/l10n/app_en.arb @@ -2652,6 +2652,24 @@ "description": "Tooltip of the button moving a step down." }, "addStepPicture": "Add a picture", + "stepVideo": "Step video", + "addStepVideo": "Add a video", + "recordStepVideo": "Record a video", + "chooseStepVideo": "Choose from the gallery", + "removeStepVideo": "Remove the video", + "videoPlay": "Play", + "videoPause": "Pause", + "videoOpenFailed": "The video cannot be opened", + "videoUnsupported": "Only MP4 or MOV videos up to a minute and 21 MB: the app does not re-encode them", + "videoAddFailed": "The video could not be added", + "stepVideoLength": "Video · {length}", + "@stepVideoLength": { + "placeholders": { + "length": { + "type": "String" + } + } + }, "@addStepPicture": { "description": "Button adding a picture to a step." }, diff --git a/apps/modusnote/lib/l10n/app_it.arb b/apps/modusnote/lib/l10n/app_it.arb index f19315f..7176ae5 100644 --- a/apps/modusnote/lib/l10n/app_it.arb +++ b/apps/modusnote/lib/l10n/app_it.arb @@ -646,6 +646,17 @@ "moveStepUp": "Sposta su", "moveStepDown": "Sposta giù", "addStepPicture": "Aggiungi una foto", + "stepVideo": "Video della fase", + "addStepVideo": "Aggiungi un video", + "recordStepVideo": "Registra un video", + "chooseStepVideo": "Scegli dalla galleria", + "removeStepVideo": "Togli il video", + "videoPlay": "Riproduci", + "videoPause": "Pausa", + "videoOpenFailed": "Impossibile aprire il video", + "videoUnsupported": "Solo video MP4 o MOV fino a un minuto e 21 MB: l'app non li ricodifica", + "videoAddFailed": "Impossibile aggiungere il video", + "stepVideoLength": "Video · {length}", "unitGram": "g", "unitKilogram": "kg", "unitMillilitre": "ml", diff --git a/apps/modusnote/lib/notes/attachments/attachments_input.dart b/apps/modusnote/lib/notes/attachments/attachments_input.dart index 30cd96f..ab1d163 100644 --- a/apps/modusnote/lib/notes/attachments/attachments_input.dart +++ b/apps/modusnote/lib/notes/attachments/attachments_input.dart @@ -19,6 +19,9 @@ final class AttachmentHooks { required this.openLink, this.addImage, this.imageSize, + this.addVideo, + this.openVideo, + this.videoLength, }); /// Picks and seals a picture; null when the person cancels. Null where @@ -34,6 +37,16 @@ final class AttachmentHooks { /// A picture's size, from the note's metadata; null when the picture is /// not known, which pictures in the text then say. final ImageHeader? Function(BlobId blob)? imageSize; + + /// Picks or records a step's video and seals it; null when the person + /// cancels. Null where videos cannot be kept, which hides the button. + final Future Function({required bool camera})? addVideo; + + /// A video's bytes, checked like a picture's. + final Future Function(BlobId blob)? openVideo; + + /// A video's length, from the note's metadata. + final Duration? Function(BlobId blob)? videoLength; } /// The pictures and links of a page: thumbnails decrypted in memory, links diff --git a/apps/modusnote/lib/notes/attachments/video_viewer.dart b/apps/modusnote/lib/notes/attachments/video_viewer.dart new file mode 100644 index 0000000..02cbac2 --- /dev/null +++ b/apps/modusnote/lib/notes/attachments/video_viewer.dart @@ -0,0 +1,127 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:video_player/video_player.dart'; + +import '../../attachments/playable_video.dart'; +import '../../l10n/generated/app_localizations.dart'; +import '../../theme/golden_ratio.dart'; +import '../../theme/modus_palette.dart'; + +/// Plays a step's video, full screen, only when asked: decrypted when the +/// viewer opens, handed to the platform's player ([playableVideo]) and +/// taken back from it when the viewer closes. +class VideoViewer extends StatefulWidget { + const VideoViewer({required this.bytes, super.key}); + + final Future bytes; + + static Future show( + BuildContext context, { + required Future bytes, + }) => Navigator.of(context).push( + MaterialPageRoute( + fullscreenDialog: true, + builder: (_) => VideoViewer(bytes: bytes), + ), + ); + + @override + State createState() => _VideoViewerState(); +} + +class _VideoViewerState extends State { + PlayableVideo? _video; + var _failed = false; + var _closed = false; + + @override + void initState() { + super.initState(); + unawaited(_open()); + } + + Future _open() async { + try { + final video = await playableVideo(await widget.bytes); + if (_closed) { + await video.release(); + return; + } + _video = video; + await video.controller.initialize(); + if (!mounted) return; + setState(() {}); + await video.controller.play(); + } on Object { + if (mounted) setState(() => _failed = true); + } + } + + @override + void dispose() { + _closed = true; + unawaited(_video?.release()); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final palette = ModusPalette.of(context); + final controller = _video?.controller; + final ready = controller != null && controller.value.isInitialized; + return Scaffold( + backgroundColor: palette.background, + appBar: AppBar( + backgroundColor: palette.background, + foregroundColor: palette.text, + title: Text(l10n.stepVideo), + ), + body: Center( + child: _failed + ? Text( + l10n.videoOpenFailed, + key: const ValueKey('video-failed'), + style: TextStyle(color: palette.text), + ) + : !ready + ? const CircularProgressIndicator() + : Column( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: AspectRatio( + aspectRatio: controller.value.aspectRatio, + child: VideoPlayer(controller), + ), + ), + VideoProgressIndicator( + controller, + allowScrubbing: true, + padding: const EdgeInsets.all(Spacing.s), + ), + ValueListenableBuilder( + valueListenable: controller, + builder: (context, value, _) => IconButton( + key: const ValueKey('video-play'), + iconSize: IconSizes.inline * 2, + color: palette.text, + tooltip: value.isPlaying + ? l10n.videoPause + : l10n.videoPlay, + icon: Icon( + value.isPlaying ? Icons.pause : Icons.play_arrow, + ), + onPressed: () => value.isPlaying + ? controller.pause() + : controller.play(), + ), + ), + ], + ), + ), + ); + } +} diff --git a/apps/modusnote/lib/notes/note_editor.dart b/apps/modusnote/lib/notes/note_editor.dart index 917425a..c87ca41 100644 --- a/apps/modusnote/lib/notes/note_editor.dart +++ b/apps/modusnote/lib/notes/note_editor.dart @@ -164,6 +164,9 @@ class NoteEditorScreenState extends State /// Pictures added since the last save, likewise. final _pictures = {}; + /// Videos added to the steps since the last save. + final _clips = {}; + final _markdown = ValueNotifier(null); /// The words of a chapter's or a journal page's text, counted as it is @@ -393,6 +396,10 @@ class NoteEditorScreenState extends State for (final blob in InlineImages.picturesOf(entry)) if (!_pictures.containsKey(blob)) ?widget.store.imageOf(blob), ]; + // A step's video is the note's own: one it no longer names goes. + final clips = [ + for (final blob in StepsValue.videosOf(entry)) ?_clips[blob], + ]; _show(SaveState.saving); // A save is not cut short by the vault locking itself. final release = AutoLockScope.maybeOf(context)?.hold(); @@ -401,6 +408,7 @@ class NoteEditorScreenState extends State entry, takes: takes, pictures: pictures, + clips: clips, newIn: _newIn, ); } on Object { @@ -415,6 +423,9 @@ class NoteEditorScreenState extends State for (final picture in pictures) { _pictures.remove(picture.id); } + for (final clip in clips) { + _clips.remove(clip.id); + } _pendingViolations = const []; // Typing during the save leaves the note to be saved again. if (identical(draft, _draft)) _dirty = false; @@ -558,6 +569,38 @@ class NoteEditorScreenState extends State return null; } + Future _addVideo({required bool camera}) async { + final images = widget.store.images; + if (images == null || !images.takesVideos) return null; + final l10n = AppLocalizations.of(context); + final messenger = ScaffoldMessenger.of(context); + final release = AutoLockScope.maybeOf(context)?.hold(); + try { + final clip = await images.chooseVideo(camera: camera); + if (clip == null) return null; + _clips[clip.id] = clip; + return clip.id; + } on UnsupportedVideoException { + messenger.showSnackBar(SnackBar(content: Text(l10n.videoUnsupported))); + } on VideoTooLargeException { + messenger.showSnackBar(SnackBar(content: Text(l10n.videoUnsupported))); + } on Object { + messenger.showSnackBar(SnackBar(content: Text(l10n.videoAddFailed))); + } finally { + release?.call(); + } + return null; + } + + Future _openVideo(BlobId blob) { + final images = widget.store.images; + final clip = _clips[blob] ?? widget.store.videoOf(blob); + if (images == null || clip == null) { + return Future.error(BlobNotFoundException(blob)); + } + return images.openVideo(clip); + } + /// Opens [recipe] to cook from; a shopping list made there is a new /// to-do note. Future _cook(DynamicEntry recipe) { @@ -568,6 +611,7 @@ class NoteEditorScreenState extends State entry: recipe, title: title, openImage: _openImage, + openVideo: widget.store.images == null ? null : _openVideo, onShopping: (List lines) async { final list = ShoppingList.of( id: _newEntryId(), @@ -713,8 +757,12 @@ class NoteEditorScreenState extends State // since the keys to save it are being released. _timer?.cancel(); _recount?.cancel(); - if (_takes.isNotEmpty || _pictures.isNotEmpty) { - widget.store.discardTakes([..._takes.values, ..._pictures.values]); + if (_takes.isNotEmpty || _pictures.isNotEmpty || _clips.isNotEmpty) { + widget.store.discardTakes([ + ..._takes.values, + ..._pictures.values, + ..._clips.values, + ]); } // [_markdown] is left to the garbage collector: the Markdown field // clears it after this frame, which must not find it disposed. @@ -968,6 +1016,18 @@ class NoteEditorScreenState extends State widget.store.imageOf(blob)) ?.metadata .info, + addVideo: + widget.store.images?.takesVideos ?? false + ? _addVideo + : null, + openVideo: widget.store.images == null + ? null + : _openVideo, + videoLength: (blob) => + (_clips[blob] ?? widget.store.videoOf(blob)) + ?.metadata + .info + .duration, ), ), if (_countedField != null) diff --git a/apps/modusnote/lib/notes/note_store.dart b/apps/modusnote/lib/notes/note_store.dart index eb10758..6d31dfe 100644 --- a/apps/modusnote/lib/notes/note_store.dart +++ b/apps/modusnote/lib/notes/note_store.dart @@ -23,6 +23,9 @@ abstract interface class NoteStore implements Listenable { KeyedImage? imageOf(BlobId id); + /// The video of a recipe's step, from the note that holds it. + KeyedVideo? videoOf(BlobId id); + /// Records takes for audio fields; null where there is nowhere to keep /// them (the web preview), which turns the record button off. NoteRecorder? get recorder; @@ -35,14 +38,15 @@ abstract interface class NoteStore implements Listenable { /// keep them (the web preview), which turns the add button off. NoteImages? get images; - /// Saves [entry] with the [takes] recorded and the [pictures] added - /// while editing it. Those it does not reference, and recordings and + /// Saves [entry] with the [takes] recorded and the [pictures] and + /// [clips] (the videos of a recipe's steps) added while editing it. Those it does not reference, and recordings and /// pictures it no longer references, are deleted. A new note is filed /// in [newIn]; an existing one stays where it is. Future save( DynamicEntry entry, { Iterable takes = const [], Iterable pictures = const [], + Iterable clips = const [], CategoryId? newIn, }); @@ -121,6 +125,14 @@ final class InMemoryNoteStore extends ChangeNotifier implements NoteStore { return null; } + @override + KeyedVideo? videoOf(BlobId id) { + for (final note in _notes.values) { + if (note.videos[id] case final video?) return video; + } + return null; + } + @override NoteRecorder? get recorder => null; @@ -135,6 +147,7 @@ final class InMemoryNoteStore extends ChangeNotifier implements NoteStore { DynamicEntry entry, { Iterable takes = const [], Iterable pictures = const [], + Iterable clips = const [], CategoryId? newIn, }) async { _notes[entry.id] = switch (_notes[entry.id]) { @@ -142,10 +155,13 @@ final class InMemoryNoteStore extends ChangeNotifier implements NoteStore { entry, known: takes, pictures: pictures, + clips: clips, category: newIn, ), final before => - before.edited(entry, takes: takes, pictures: pictures).restored(), + before + .edited(entry, takes: takes, pictures: pictures, clips: clips) + .restored(), }; notifyListeners(); } @@ -216,6 +232,7 @@ final class InMemoryNoteStore extends ChangeNotifier implements NoteStore { }, known: note.recordings.values, pictures: note.images.values, + clips: note.videos.values, category: note.category, ); copies[id] = copy; diff --git a/apps/modusnote/lib/notes/recipes/cooking_mode.dart b/apps/modusnote/lib/notes/recipes/cooking_mode.dart index d3611ff..94ae194 100644 --- a/apps/modusnote/lib/notes/recipes/cooking_mode.dart +++ b/apps/modusnote/lib/notes/recipes/cooking_mode.dart @@ -8,6 +8,7 @@ import '../../l10n/generated/app_localizations.dart'; import '../../theme/golden_ratio.dart'; import '../../theme/modus_palette.dart'; import '../attachments/attachments_input.dart'; +import '../attachments/video_viewer.dart'; import '../markdown/markdown_document.dart'; import '../markdown/markdown_view.dart'; import 'recipe_text.dart'; @@ -44,6 +45,7 @@ class CookingModeScreen extends StatefulWidget { required this.entry, required this.title, required this.openImage, + this.openVideo, this.onShopping, super.key, }); @@ -52,6 +54,9 @@ class CookingModeScreen extends StatefulWidget { final String title; final Future Function(BlobId blob) openImage; + /// A step's video; null where videos cannot be opened. + final Future Function(BlobId blob)? openVideo; + /// Saves a shopping list of [lines]; null where notes cannot be saved. final Future Function(List lines)? onShopping; @@ -60,6 +65,7 @@ class CookingModeScreen extends StatefulWidget { required DynamicEntry entry, required String title, required Future Function(BlobId blob) openImage, + Future Function(BlobId blob)? openVideo, Future Function(List lines)? onShopping, }) => Navigator.of(context).push( MaterialPageRoute( @@ -68,6 +74,7 @@ class CookingModeScreen extends StatefulWidget { entry: entry, title: title, openImage: openImage, + openVideo: openVideo, onShopping: onShopping, ), ), @@ -394,6 +401,19 @@ class _CookingModeScreenState extends State { ), ), ), + if ((step.video, widget.openVideo) case (final video?, final open?)) + Padding( + padding: const EdgeInsets.only(top: Spacing.m), + child: Align( + alignment: Alignment.centerLeft, + child: FilledButton.tonalIcon( + key: const ValueKey('cooking-video'), + icon: const Icon(Icons.play_circle_outline), + label: Text(AppLocalizations.of(context).stepVideo), + onPressed: () => VideoViewer.show(context, bytes: open(video)), + ), + ), + ), Padding( padding: const EdgeInsets.only(top: Spacing.m), child: Align( diff --git a/apps/modusnote/lib/notes/recipes/recipe_inputs.dart b/apps/modusnote/lib/notes/recipes/recipe_inputs.dart index 7e6cff2..88a47b0 100644 --- a/apps/modusnote/lib/notes/recipes/recipe_inputs.dart +++ b/apps/modusnote/lib/notes/recipes/recipe_inputs.dart @@ -1,5 +1,6 @@ import 'dart:typed_data'; +import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:schema_dynamic_content/schema_dynamic_content.dart'; @@ -8,6 +9,7 @@ import '../../theme/golden_ratio.dart'; import '../../theme/modus_palette.dart'; import '../attachments/attachment_dialogs.dart'; import '../attachments/attachments_input.dart'; +import '../attachments/video_viewer.dart'; import 'recipe_text.dart'; /// Reports a field that may hold input that cannot become a value yet. @@ -383,14 +385,17 @@ class _IngredientsInputState extends State { final class _StepRow { _StepRow([PreparationStep? step]) : text = TextEditingController(text: step?.text ?? ''), - pictures = [...?step?.pictures]; + pictures = [...?step?.pictures], + video = step?.video; final key = UniqueKey(); final TextEditingController text; final List pictures; + BlobId? video; final focus = FocusNode(); - bool get blank => text.text.trim().isEmpty && pictures.isEmpty; + bool get blank => + text.text.trim().isEmpty && pictures.isEmpty && video == null; void dispose() { text.dispose(); @@ -445,7 +450,11 @@ class _StepsInputState extends State { final steps = [ for (final row in _rows) if (!row.blank) - PreparationStep(row.text.text.trim(), pictures: row.pictures), + PreparationStep( + row.text.text.trim(), + pictures: row.pictures, + video: row.video, + ), ]; widget.onChanged(steps.isEmpty ? null : StepsValue(steps)); } @@ -476,6 +485,103 @@ class _StepsInputState extends State { _update(() => row.pictures.add(ImageAttachment(blob))); } + Future _addVideo( + _StepRow row, + Future Function({required bool camera}) add, { + required bool camera, + }) async { + final blob = await add(camera: camera); + if (blob == null || !mounted) return; + _update(() => row.video = blob); + } + + /// «0:42»: a clip is at most a minute. + static String _length(Duration length) => + '${length.inMinutes}:${(length.inSeconds % 60).toString().padLeft(2, '0')}'; + + Widget _video(BuildContext context, _StepRow row, int index) { + final l10n = AppLocalizations.of(context); + final palette = ModusPalette.of(context); + final video = row.video; + final open = widget.hooks.openVideo; + if (video != null) { + final length = widget.hooks.videoLength?.call(video); + return Padding( + padding: const EdgeInsets.only(top: Spacing.s), + child: Row( + children: [ + TextButton.icon( + key: ValueKey('step-video-$index'), + icon: const Icon(Icons.play_circle_outline), + label: Text( + length == null + ? l10n.stepVideo + : l10n.stepVideoLength(_length(length)), + ), + onPressed: open == null + ? null + : () => VideoViewer.show(context, bytes: open(video)), + ), + const Spacer(), + IconButton( + key: ValueKey('step-remove-video-$index'), + icon: const Icon(Icons.close, size: IconSizes.inline), + color: palette.muted, + tooltip: l10n.removeStepVideo, + onPressed: () => _update(() => row.video = null), + ), + ], + ), + ); + } + final add = widget.hooks.addVideo; + if (add == null) return const SizedBox.shrink(); + return Align( + alignment: Alignment.centerLeft, + child: PopupMenuButton( + key: ValueKey('step-add-video-$index'), + tooltip: l10n.addStepVideo, + onSelected: (camera) => _addVideo(row, add, camera: camera), + itemBuilder: (_) => [ + // A browser here has no camera of its own. + if (!kIsWeb) + PopupMenuItem( + key: const ValueKey('step-record-video'), + value: true, + child: Text(l10n.recordStepVideo), + ), + PopupMenuItem( + key: const ValueKey('step-choose-video'), + value: false, + child: Text(l10n.chooseStepVideo), + ), + ], + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Spacing.s, + vertical: Spacing.xs, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.videocam_outlined, + size: IconSizes.inline, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(width: Spacing.xs), + Text( + l10n.addStepVideo, + style: Theme.of(context).textTheme.labelLarge + ?.copyWith(color: Theme.of(context).colorScheme.primary), + ), + ], + ), + ), + ), + ); + } + @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context); @@ -593,6 +699,7 @@ class _StepsInputState extends State { : () => _addPicture(row, addImage), ), ), + _video(context, row, index), ], ), ), diff --git a/apps/modusnote/lib/publishing/publication_media.dart b/apps/modusnote/lib/publishing/publication_media.dart index a8e32db..fac5a59 100644 --- a/apps/modusnote/lib/publishing/publication_media.dart +++ b/apps/modusnote/lib/publishing/publication_media.dart @@ -9,7 +9,9 @@ import 'package:schema_dynamic_content/schema_dynamic_content.dart'; /// encoded again by [reencode] (no metadata of the original survives, see /// `reencodePicture`); a recording is passed as it is only when it is Opus /// in Ogg or WebM, the containers serv.pub takes (a WAV or AAC take is left -/// out). +/// out); a step's video is opened and cleaned again ([VideoScrubber]), +/// though it was cleaned before it was sealed: what leaves the device is +/// checked where it leaves. final class VaultPublicationMedia implements PublicationMedia { VaultPublicationMedia({ required this._imageOf, @@ -17,6 +19,8 @@ final class VaultPublicationMedia implements PublicationMedia { required this._openImage, required this._openRecording, required this._reencode, + this._videoOf, + this._openVideo, }); final KeyedImage? Function(BlobId blob) _imageOf; @@ -24,6 +28,8 @@ final class VaultPublicationMedia implements PublicationMedia { final Future Function(KeyedImage image) _openImage; final Stream Function(KeyedRecording take) _openRecording; final Future Function(Uint8List picture) _reencode; + final KeyedVideo? Function(BlobId blob)? _videoOf; + final Future Function(KeyedVideo video)? _openVideo; /// serv.pub's limit for one file. static const maxBytes = 21 << 20; @@ -40,6 +46,18 @@ final class VaultPublicationMedia implements PublicationMedia { original.fillRange(0, original.length, 0); } } + if ((_videoOf?.call(blob), _openVideo) case (final video?, final open?)) { + final original = await open(video); + try { + final clean = VideoScrubber.scrub(original); + if (clean.length > maxBytes) return null; + return PreparedMedia(MediaKind.mp4, clean); + } on BlobException { + return null; + } finally { + original.fillRange(0, original.length, 0); + } + } if (_recordingOf(blob) case final take?) { final kind = switch (take.metadata.format) { AudioFormat.opusOgg => MediaKind.ogg, diff --git a/apps/modusnote/lib/publishing/publish_sheet.dart b/apps/modusnote/lib/publishing/publish_sheet.dart index 0437a4d..be64391 100644 --- a/apps/modusnote/lib/publishing/publish_sheet.dart +++ b/apps/modusnote/lib/publishing/publish_sheet.dart @@ -116,6 +116,7 @@ class _PublishSheetState extends State { bool get _hasPictures => AttachmentsValue.imagesOf(widget.entry).isNotEmpty || + StepsValue.videosOf(widget.entry).isNotEmpty || widget.entry.attributes.values.any( (v) => v is TextValue && InlineImages.find(v.text).isNotEmpty, ); diff --git a/apps/modusnote/lib/vault/vault_gate.dart b/apps/modusnote/lib/vault/vault_gate.dart index 0b69dbe..8fec123 100644 --- a/apps/modusnote/lib/vault/vault_gate.dart +++ b/apps/modusnote/lib/vault/vault_gate.dart @@ -409,6 +409,10 @@ class _VaultGateState extends State with WidgetsBindingObserver { ); }, reencode: reencodePicture, + videoOf: store.videoOf, + openVideo: (video) => + store.images?.openVideo(video) ?? + Future.error(BlobNotFoundException(video.id)), ), isConfirmed: () => widget.keeper.isConfirmed(vault), ), diff --git a/apps/modusnote/lib/vault/vault_note_store.dart b/apps/modusnote/lib/vault/vault_note_store.dart index 3471c3a..1353d57 100644 --- a/apps/modusnote/lib/vault/vault_note_store.dart +++ b/apps/modusnote/lib/vault/vault_note_store.dart @@ -93,10 +93,12 @@ final class VaultNoteStore extends ChangeNotifier implements NoteStore { // the notes change. List? _entries; Map? _images; + Map? _videos; void _notesChanged() { _entries = null; _images = null; + _videos = null; } @override @@ -136,6 +138,19 @@ final class VaultNoteStore extends ChangeNotifier implements NoteStore { return _images![id]; } + @override + KeyedVideo? videoOf(BlobId id) { + if (_videos == null) { + final videos = _videos = {}; + for (final note in _notes.values) { + for (final MapEntry(:key, :value) in note.videos.entries) { + videos.putIfAbsent(key, () => value); + } + } + } + return _videos![id]; + } + @override CategoryTree get categories => _tree ??= CategoryTree(_categories.values); @@ -148,6 +163,7 @@ final class VaultNoteStore extends ChangeNotifier implements NoteStore { DynamicEntry entry, { Iterable takes = const [], Iterable pictures = const [], + Iterable clips = const [], CategoryId? newIn, }) async { final before = _notes[entry.id]; @@ -158,9 +174,12 @@ final class VaultNoteStore extends ChangeNotifier implements NoteStore { entry, known: takes, pictures: pictures, + clips: clips, category: newIn, ) - : before.edited(entry, takes: takes, pictures: pictures).restored(); + : before + .edited(entry, takes: takes, pictures: pictures, clips: clips) + .restored(); await _put(after); // Only once the note no longer points at them, and only what no note // points at: a picture pasted from one note's text into another's @@ -171,7 +190,7 @@ final class VaultNoteStore extends ChangeNotifier implements NoteStore { : RecordedNote.released(before: before, after: after).difference(kept); await _delete({ ...released, - for (final blob in [...takes, ...pictures]) + for (final blob in [...takes, ...pictures, ...clips]) if (!kept.contains(blob.id)) blob.id, }); await _release(released); @@ -238,6 +257,7 @@ final class VaultNoteStore extends ChangeNotifier implements NoteStore { entry, known: note.recordings.values, pictures: note.images.values, + clips: note.videos.values, category: note.category, ), ); diff --git a/apps/modusnote/pubspec.yaml b/apps/modusnote/pubspec.yaml index 7363ef8..b6041a9 100644 --- a/apps/modusnote/pubspec.yaml +++ b/apps/modusnote/pubspec.yaml @@ -33,6 +33,7 @@ dependencies: web: ^1.1.1 flutter_local_notifications: 22.3.2 timezone: ^0.11.0 + video_player: ^2.14.1 dev_dependencies: crypto: ^3.0.7 diff --git a/apps/modusnote/test/notes/cooking_mode_test.dart b/apps/modusnote/test/notes/cooking_mode_test.dart index 7625014..36d1831 100644 --- a/apps/modusnote/test/notes/cooking_mode_test.dart +++ b/apps/modusnote/test/notes/cooking_mode_test.dart @@ -23,7 +23,7 @@ DynamicEntry recipe({bool withServings = true}) => switch (DynamicEntry.create( ]), FieldKey('steps'): StepsValue([ PreparationStep('Impasta e lascia lievitare **2 ore**.'), - PreparationStep('Inforna per 40 minuti.'), + PreparationStep('Inforna per 40 minuti.', video: BlobId('v' * 32)), ]), }, at: at, @@ -102,12 +102,17 @@ void main() { late List> shopped; setUp(() => shopped = []); - Future open(WidgetTester tester, {DynamicEntry? entry}) => pumpApp( + Future open( + WidgetTester tester, { + DynamicEntry? entry, + bool videos = true, + }) => pumpApp( tester, CookingModeScreen( entry: entry ?? recipe(), title: 'Pane', openImage: (_) async => Uint8List(0), + openVideo: videos ? (_) async => Uint8List(0) : null, onShopping: (lines) async => shopped.add(lines), ), ); @@ -177,6 +182,19 @@ void main() { expect(find.text('Fase 2 di 2'), findsOneWidget); expect(find.text('Timer 40 min'), findsOneWidget); expect(find.text('Fatto'), findsOneWidget); + // The step's video plays only when asked. + expect(find.byKey(const ValueKey('cooking-video')), findsOneWidget); + }); + + testWidgets('a video is not offered where it cannot be opened', ( + tester, + ) async { + await open(tester, videos: false); + await tester.tap(find.byKey(const ValueKey('cooking-next'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('cooking-next'))); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('cooking-video')), findsNothing); }); testWidgets('a timer counts down and says when time is up', (tester) async { diff --git a/apps/modusnote/test/notes/recipe_editor_test.dart b/apps/modusnote/test/notes/recipe_editor_test.dart index 21b8fe4..cd8c070 100644 --- a/apps/modusnote/test/notes/recipe_editor_test.dart +++ b/apps/modusnote/test/notes/recipe_editor_test.dart @@ -16,6 +16,7 @@ final ingredients = FieldKey('ingredients'); final steps = FieldKey('steps'); final methods = FieldKey('methods'); final picture = BlobId('p' * 32); +final clip = BlobId('v' * 32); void main() { late List drafts; @@ -25,6 +26,7 @@ void main() { WidgetTester tester, { Map values = const {}, Future Function()? addImage, + Future Function({required bool camera})? addVideo, }) => pumpApp( tester, Scaffold( @@ -37,6 +39,10 @@ void main() { openImage: (_) async => Uint8List(0), openLink: (_) async => false, addImage: addImage, + addVideo: addVideo, + openVideo: (_) async => Uint8List(0), + videoLength: (blob) => + blob == clip ? const Duration(seconds: 42) : null, ), ), ), @@ -136,6 +142,46 @@ void main() { expect(find.text('Fase 2'), findsOneWidget); }); + testWidgets('a step is given a video, recorded or chosen, and loses it', ( + tester, + ) async { + final asked = []; + await render( + tester, + addVideo: ({required camera}) async { + asked.add(camera); + return clip; + }, + ); + await tester.enterText(input('step-text-0'), 'Impasta'); + await tester.tap(input('step-add-video-0')); + await tester.pumpAndSettle(); + expect(find.text('Registra un video'), findsOneWidget); + await tester.tap(find.text('Registra un video')); + await tester.pumpAndSettle(); + + expect(asked, [true]); + expect( + drafts.last.values[steps], + StepsValue([PreparationStep('Impasta', video: clip)]), + ); + expect(find.text('Video · 0:42'), findsOneWidget); + // One video a step: the button gives way to the clip. + expect(input('step-add-video-0'), findsNothing); + + await tester.tap(input('step-remove-video-0')); + await tester.pump(); + expect(drafts.last.values[steps], StepsValue([PreparationStep('Impasta')])); + expect(input('step-add-video-0'), findsOneWidget); + }); + + testWidgets('without a place for videos there is no video button', ( + tester, + ) async { + await render(tester); + expect(input('step-add-video-0'), findsNothing); + }); + testWidgets('methods are chips to turn on and off', (tester) async { // A new recipe shows its details open. await render(tester); diff --git a/packages/blob_storage_media/lib/blob_storage_media.dart b/packages/blob_storage_media/lib/blob_storage_media.dart index 408bccb..35fc6f0 100644 --- a/packages/blob_storage_media/lib/blob_storage_media.dart +++ b/packages/blob_storage_media/lib/blob_storage_media.dart @@ -12,6 +12,7 @@ export 'src/application/ciphertext_blob_store.dart'; export 'src/application/encrypted_blob_storage.dart'; export 'src/application/image_storage.dart'; export 'src/application/recording_playback.dart'; +export 'src/application/video_storage.dart'; export 'src/core/audio_attachment.dart'; export 'src/core/audio_format.dart'; export 'src/core/blob_exception.dart'; @@ -23,3 +24,4 @@ export 'src/core/portable_int64.dart'; export 'src/core/recorded_note.dart'; export 'src/core/recording_state.dart'; export 'src/core/stored_blob.dart'; +export 'src/core/video_format.dart'; diff --git a/packages/blob_storage_media/lib/src/application/video_storage.dart b/packages/blob_storage_media/lib/src/application/video_storage.dart new file mode 100644 index 0000000..7f6d93d --- /dev/null +++ b/packages/blob_storage_media/lib/src/application/video_storage.dart @@ -0,0 +1,69 @@ +import 'dart:typed_data'; + +import 'package:identity_cryptography/identity_cryptography.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +import '../core/blob_exception.dart'; +import '../core/video_format.dart'; +import 'encrypted_blob_storage.dart'; + +/// Use case: the short videos of a recipe's steps in and out of encrypted +/// blobs, whole and in memory (21 MiB at most). +/// +/// A video is cleaned before it is sealed ([VideoScrubber]): the vault +/// never holds the location or the device a phone wrote into it. It is +/// checked again after it is opened, like a picture: the metadata comes +/// from whoever wrote the note. +final class VideoStorage { + VideoStorage({required this._storage}); + + final EncryptedBlobStorage _storage; + + /// Seals a clean copy of [bytes] into blob [id]. Throws + /// [UnsupportedVideoException] or [VideoTooLargeException] without + /// writing anything. + Future seal( + Uint8List bytes, { + required BlobId id, + required SymmetricKey contentKey, + required DateTime at, + }) async { + final clean = VideoScrubber.scrub(bytes); + final info = VideoProbe.probe(clean); + final blob = await _storage.write( + Stream.value(clean), + id: id, + contentKey: contentKey, + ); + return VideoMetadata(blob: blob, info: info, addedAt: at.toUtc()); + } + + /// The video's bytes, authenticated chunk by chunk. Throws + /// [MalformedBlobException] when they are not the video the metadata + /// describes. + Future open( + VideoMetadata video, { + required SymmetricKey contentKey, + }) async { + final out = BytesBuilder(copy: false); + await for (final chunk in _storage.read( + video.blob, + contentKey: contentKey, + )) { + out.add(chunk); + } + final bytes = out.takeBytes(); + final VideoHeader info; + try { + info = VideoProbe.probe(bytes); + } on UnsupportedVideoException { + throw const MalformedBlobException('not the video described'); + } on VideoTooLargeException { + throw const MalformedBlobException('not the video described'); + } + if (info != video.info) { + throw const MalformedBlobException('not the video described'); + } + return bytes; + } +} diff --git a/packages/blob_storage_media/lib/src/core/blob_exception.dart b/packages/blob_storage_media/lib/src/core/blob_exception.dart index f746f16..50d9d94 100644 --- a/packages/blob_storage_media/lib/src/core/blob_exception.dart +++ b/packages/blob_storage_media/lib/src/core/blob_exception.dart @@ -90,6 +90,24 @@ final class ImageTooLargeException extends BlobException { String get message => 'picture too large'; } +/// Bytes that are not an MP4 (or QuickTime) video this app keeps: one +/// moov, its samples in mdat, a video track, not fragmented. +final class UnsupportedVideoException extends BlobException { + const UnsupportedVideoException(); + + @override + String get message => 'not a video this app keeps'; +} + +/// A video past `VideoProbe.maxBytes`, `VideoProbe.maxDuration` or the +/// limits in pixels: the app does not re-encode, so it refuses. +final class VideoTooLargeException extends BlobException { + const VideoTooLargeException(); + + @override + String get message => 'video too long or too large'; +} + /// A recording longer than playback holds in memory /// (`DecodedAudio.maxDuration`). final class RecordingTooLongException extends BlobException { diff --git a/packages/blob_storage_media/lib/src/core/recorded_note.dart b/packages/blob_storage_media/lib/src/core/recorded_note.dart index bd80bc1..d350278 100644 --- a/packages/blob_storage_media/lib/src/core/recorded_note.dart +++ b/packages/blob_storage_media/lib/src/core/recorded_note.dart @@ -12,6 +12,7 @@ import 'blob_exception.dart'; import 'blob_metadata.dart'; import 'image_format.dart'; import 'portable_int64.dart'; +import 'video_format.dart'; /// A blob a note references, with the GroupKey epoch whose key sealed it: /// what replicating, downloading or deleting it needs, whatever it holds. @@ -74,12 +75,37 @@ final class KeyedImage implements KeyedBlob { int get hashCode => Object.hash(epoch, metadata); } +/// A step's video with the GroupKey epoch whose key sealed it, like +/// [KeyedRecording]. +@immutable +final class KeyedVideo implements KeyedBlob { + const KeyedVideo({required this.epoch, required this.metadata}); + + @override + final KeyEpoch epoch; + final VideoMetadata metadata; + + @override + SealedBlob get blob => metadata.blob; + + @override + BlobId get id => metadata.id; + + @override + bool operator ==(Object other) => + other is KeyedVideo && other.epoch == epoch && other.metadata == metadata; + + @override + int get hashCode => Object.hash(epoch, metadata); +} + /// A note together with the metadata of every recording it references, /// the plaintext the vault seals as one record. Holding them together is /// what keeps format, length and key id out of the server's sight. /// /// Invariant: [recordings] has exactly the recordings the entry -/// references, and [images] exactly its pictures. +/// references, [images] exactly its pictures and [videos] exactly the +/// videos of its steps. /// /// A note in the trash is still whole, recordings included, so restoring /// it brings everything back; only deleting it for good (a tombstone in the @@ -93,10 +119,12 @@ final class RecordedNote { this.entry, Map recordings, { Map images = const {}, + Map videos = const {}, DateTime? trashedAt, this.category, }) : recordings = Map.unmodifiable(recordings), images = Map.unmodifiable(images), + videos = Map.unmodifiable(videos), trashedAt = trashedAt?.toUtc(); /// Pairs [entry] with the metadata of the blobs it references, picked @@ -106,6 +134,7 @@ final class RecordedNote { DynamicEntry entry, { Iterable known = const [], Iterable pictures = const [], + Iterable clips = const [], CategoryId? category, }) { final byId = {for (final take in known) take.id: take}; @@ -122,10 +151,18 @@ final class RecordedNote { imagesById[id] ?? (throw ArgumentError.value(id.value, 'entry', 'unknown picture')); } + final clipsById = {for (final clip in clips) clip.id: clip}; + final videos = {}; + for (final id in StepsValue.videosOf(entry)) { + videos[id] = + clipsById[id] ?? + (throw ArgumentError.value(id.value, 'entry', 'unknown video')); + } return RecordedNote._( entry, recordings, images: images, + videos: videos, category: category, ); } @@ -138,8 +175,15 @@ final class RecordedNote { /// The pictures of the note's attachments. final Map images; - /// Every blob the note needs: its recordings and its pictures. - Iterable get blobs => [...recordings.values, ...images.values]; + /// The videos of the note's steps. + final Map videos; + + /// Every blob the note needs: its recordings, pictures and videos. + Iterable get blobs => [ + ...recordings.values, + ...images.values, + ...videos.values, + ]; /// When the note was moved to the trash, in UTC; null when it is not. final DateTime? trashedAt; @@ -155,19 +199,26 @@ final class RecordedNote { entry, recordings, images: images, + videos: videos, trashedAt: at, category: category, ); /// The same note back out of the trash, in the category it had. - RecordedNote restored() => - RecordedNote._(entry, recordings, images: images, category: category); + RecordedNote restored() => RecordedNote._( + entry, + recordings, + images: images, + videos: videos, + category: category, + ); /// The same note filed in [category] (null: in none). RecordedNote filedIn(CategoryId? category) => RecordedNote._( entry, recordings, images: images, + videos: videos, trashedAt: trashedAt, category: category, ); @@ -195,22 +246,25 @@ final class RecordedNote { } /// The same note after an edit of its fields, with [takes] recorded and - /// [pictures] added during the edit: recordings and pictures it no - /// longer references go. + /// [pictures] and [clips] added during the edit: blobs it no longer + /// references go. RecordedNote edited( DynamicEntry next, { Iterable takes = const [], Iterable pictures = const [], + Iterable clips = const [], }) { final note = RecordedNote.compose( next, known: [...recordings.values, ...takes], pictures: [...images.values, ...pictures], + clips: [...videos.values, ...clips], ); return RecordedNote._( note.entry, note.recordings, images: note.images, + videos: note.videos, trashedAt: trashedAt, category: category, ); @@ -236,13 +290,16 @@ final class RecordedNote { /// bit 1 as needed, then after the category `count(u16) | pictures`; /// * in version 5, the same flags with bit 3 (digests) always set and /// bit 2 as needed, then after the pictures, for each recording and then -/// each picture, `has(u8) | digest(32)` when `has` is 1. +/// each picture, `has(u8) | digest(32)` when `has` is 1; +/// * in version 6, the same flags with bit 4 (videos) always set and bit +/// 3 as needed, then after the pictures `count(u16) | videos`, and the +/// digests of the recordings, the pictures and then the videos. /// /// Each note is written in the oldest version that holds it: one outside /// the trash and any category is version 1, byte for byte what apps /// without a trash read, a trashed one outside any category version 2, -/// only a note with pictures version 4 and only one naming a blob digest -/// version 5. +/// only a note with pictures version 4, only one naming a blob digest +/// version 5 and only one with a video version 6. /// Older apps see a note in a later version as unreadable, so it leaves /// their library until they are updated. Decoding treats its input as /// hostile and throws only [MalformedBlobException]. @@ -252,27 +309,38 @@ abstract final class RecordedNoteCodec { static const _filedVersion = 3; static const _picturedVersion = 4; static const _digestedVersion = 5; + static const _videoVersion = 6; static const _trashedFlag = 1; static const _filedFlag = 2; static const _picturesFlag = 4; static const _digestsFlag = 8; + static const _videosFlag = 16; static const _maxRecordings = 64; static const _maxImages = AttachmentsFieldType.maxAllowedItems; + static const _maxVideos = StepsFieldType.maxAllowedItems; static Uint8List encode(RecordedNote note) { final bytes = _encodeBody(note.entry, note.recordings); final trashedAt = note.trashedAt; final category = note.category; final images = note.images.values; + final videos = note.videos.values; final digests = [ for (final take in note.recordings.values) take.metadata.blob.digest, for (final image in images) image.metadata.blob.digest, + for (final video in videos) video.metadata.blob.digest, ]; final digested = digests.any((digest) => digest != null); - if (trashedAt == null && category == null && images.isEmpty && !digested) { + if (trashedAt == null && + category == null && + images.isEmpty && + videos.isEmpty && + !digested) { return bytes; } - final version = digested + final version = videos.isNotEmpty + ? _videoVersion + : digested ? _digestedVersion : images.isNotEmpty ? _picturedVersion @@ -287,7 +355,8 @@ abstract final class RecordedNoteCodec { (trashedAt == null ? 0 : _trashedFlag) | (category == null ? 0 : _filedFlag) | (images.isEmpty ? 0 : _picturesFlag) | - (digested ? _digestsFlag : 0), + (digested ? _digestsFlag : 0) | + (videos.isEmpty ? 0 : _videosFlag), ); } if (trashedAt != null) { @@ -300,6 +369,7 @@ abstract final class RecordedNoteCodec { ..add(id); } if (images.isNotEmpty) _writeImages(out, images); + if (videos.isNotEmpty) _writeVideos(out, videos); if (digested) { for (final digest in digests) { if (digest == null) { @@ -349,6 +419,24 @@ abstract final class RecordedNoteCodec { } } + static void _writeVideos(BytesBuilder out, Iterable videos) { + out.add(_uint(2, videos.length)); + for (final video in videos) { + final metadata = video.metadata; + _blob(out, utf8.encode(metadata.id.value)); + out + ..add(_uint(4, video.epoch.value)) + ..add(metadata.blob.keyId.bytes) + ..add(_uint(8, metadata.blob.plaintextLength)); + _blob(out, utf8.encode(metadata.format.wireName)); + out + ..add(_uint(4, metadata.info.width)) + ..add(_uint(4, metadata.info.height)) + ..add(_uint(8, metadata.info.duration.inMicroseconds)) + ..add(_uint(8, metadata.addedAt.microsecondsSinceEpoch)); + } + } + static Uint8List _encodeBody( DynamicEntry entry, Map recordings, @@ -378,7 +466,7 @@ abstract final class RecordedNoteCodec { try { final reader = _Reader(bytes); final version = reader.uint(1); - if (version < _version || version > _digestedVersion) { + if (version < _version || version > _videoVersion) { throw const MalformedBlobException('unknown note version'); } final entryBytes = reader.blob(); @@ -404,9 +492,16 @@ abstract final class RecordedNoteCodec { _filedVersion => _filedFlag, _picturedVersion => _picturesFlag, _digestedVersion => _digestsFlag, + _videoVersion => _videosFlag, _ => 0, }; final allowed = switch (version) { + _videoVersion => + _trashedFlag | + _filedFlag | + _picturesFlag | + _digestsFlag | + _videosFlag, _digestedVersion => _trashedFlag | _filedFlag | _picturesFlag | _digestsFlag, _picturedVersion => _trashedFlag | _filedFlag | _picturesFlag, @@ -434,6 +529,22 @@ abstract final class RecordedNoteCodec { images[image.id] = image; } } + final videos = {}; + if (flags & _videosFlag != 0) { + final count = reader.uint(2); + if (count == 0 || count > _maxVideos) { + throw const MalformedBlobException('too many videos'); + } + for (var i = 0; i < count; i++) { + final video = _readVideo(reader); + if (videos.containsKey(video.id) || + images.containsKey(video.id) || + recordings.containsKey(video.id)) { + throw const MalformedBlobException('duplicate video'); + } + videos[video.id] = video; + } + } if (flags & _digestsFlag != 0) { var any = false; ContentDigest? next() { @@ -450,6 +561,9 @@ abstract final class RecordedNoteCodec { for (final MapEntry(:key, value: image) in images.entries) { images[key] = _imageWith(image, next()); } + for (final MapEntry(:key, value: video) in videos.entries) { + videos[key] = _videoWith(video, next()); + } if (!any) throw const MalformedBlobException('digests without one'); } reader.finish(); @@ -459,6 +573,7 @@ abstract final class RecordedNoteCodec { entry, recordings, images, + videos, trashedAt: trashedAt, category: category, ), @@ -471,6 +586,8 @@ abstract final class RecordedNoteCodec { throw const MalformedBlobException('malformed recording'); } on ImageTooLargeException { throw const MalformedBlobException('malformed picture'); + } on VideoTooLargeException { + throw const MalformedBlobException('malformed video'); } on InvalidSchemaException { throw const MalformedBlobException('malformed recording id'); } on CollaborationException { @@ -485,7 +602,8 @@ abstract final class RecordedNoteCodec { static RecordedNote _paired( DynamicEntry entry, Map recordings, - Map images, { + Map images, + Map videos, { DateTime? trashedAt, CategoryId? category, }) { @@ -499,10 +617,15 @@ abstract final class RecordedNoteCodec { !pictured.containsAll(images.keys)) { throw const MalformedBlobException('pictures do not match the note'); } + final filmed = StepsValue.videosOf(entry).toSet(); + if (filmed.length != videos.length || !filmed.containsAll(videos.keys)) { + throw const MalformedBlobException('videos do not match the note'); + } return RecordedNote._( entry, recordings, images: images, + videos: videos, trashedAt: trashedAt, category: category, ); @@ -539,6 +662,35 @@ abstract final class RecordedNoteCodec { ), ); + static KeyedVideo _videoWith(KeyedVideo video, ContentDigest? digest) => + KeyedVideo( + epoch: video.epoch, + metadata: VideoMetadata( + blob: _blobWith(video.metadata.blob, digest), + info: video.metadata.info, + addedAt: video.metadata.addedAt, + ), + ); + + static KeyedVideo _readVideo(_Reader reader) { + final id = BlobId(utf8.decode(reader.blob())); + final epoch = KeyEpoch(reader.uint(4)); + final keyId = SubkeyId.fromBytes(reader.bytes(SubkeyId.length)); + final length = reader.uint(8); + final format = VideoFormat.fromWireName(utf8.decode(reader.blob())); + final width = reader.uint(4); + final height = reader.uint(4); + final duration = Duration(microseconds: reader.uint(8)); + return KeyedVideo( + epoch: epoch, + metadata: VideoMetadata( + blob: SealedBlob(id: id, keyId: keyId, plaintextLength: length), + info: VideoHeader(format, width, height, duration), + addedAt: _time(reader), + ), + ); + } + static KeyedImage _readImage(_Reader reader) { final id = BlobId(utf8.decode(reader.blob())); final epoch = KeyEpoch(reader.uint(4)); diff --git a/packages/blob_storage_media/lib/src/core/video_format.dart b/packages/blob_storage_media/lib/src/core/video_format.dart new file mode 100644 index 0000000..184686b --- /dev/null +++ b/packages/blob_storage_media/lib/src/core/video_format.dart @@ -0,0 +1,521 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:meta/meta.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +import 'blob_exception.dart'; +import 'blob_metadata.dart'; +import 'portable_int64.dart'; + +/// The video format a step can hold: MP4 (and QuickTime, its parent), +/// what phones record and browsers play. Anything else is refused before +/// it is sealed: the app never re-encodes. +enum VideoFormat { + mp4('mp4', 'video/mp4'); + + const VideoFormat(this.wireName, this.mimeType); + + /// Stable name for persisted metadata; independent of enum order. + final String wireName; + final String mimeType; + + static VideoFormat fromWireName(String wireName) { + for (final format in values) { + if (format.wireName == wireName) return format; + } + throw const InvalidBlobMetadataException('unknown video format'); + } +} + +/// A video's format, size in pixels and length, as its own boxes state +/// them. +@immutable +final class VideoHeader { + VideoHeader(this.format, this.width, this.height, this.duration) { + if (width < 1 || + height < 1 || + width > VideoProbe.maxSide || + height > VideoProbe.maxSide || + duration.isNegative || + duration > VideoProbe.maxDuration) { + throw const VideoTooLargeException(); + } + } + + final VideoFormat format; + final int width; + final int height; + final Duration duration; + + @override + bool operator ==(Object other) => + other is VideoHeader && + other.format == format && + other.width == width && + other.height == height && + other.duration == duration; + + @override + int get hashCode => Object.hash(format, width, height, duration); + + @override + String toString() => + 'VideoHeader(${format.wireName}, $width×$height, ' + '${duration.inMilliseconds} ms)'; +} + +/// Describes one encrypted video blob; like [BlobMetadata], it travels +/// only inside the sealed note. +@immutable +final class VideoMetadata { + VideoMetadata({ + required this.blob, + required this.info, + required this.addedAt, + }) { + if (blob.plaintextLength > VideoProbe.maxBytes) { + throw const InvalidBlobMetadataException('video too large'); + } + if (!addedAt.isUtc) { + throw const InvalidBlobMetadataException('addedAt must be UTC'); + } + } + + final SealedBlob blob; + final VideoHeader info; + final DateTime addedAt; + + BlobId get id => blob.id; + + VideoFormat get format => info.format; + + @override + bool operator ==(Object other) => + other is VideoMetadata && + other.blob == blob && + other.info == info && + other.addedAt == addedAt; + + @override + int get hashCode => Object.hash(blob, info, addedAt); +} + +/// One box of an ISO base media file: where it starts, where its content +/// starts and where it ends, in the file. +final class _Box { + _Box(this.type, this.start, this.content, this.end); + + final String type; + final int start; + final int content; + final int end; +} + +/// Reads boxes defensively: every size is checked against its parent, so +/// hostile bytes can only be refused. +final class _Boxes { + _Boxes(this.bytes) : _data = ByteData.sublistView(bytes); + + final Uint8List bytes; + final ByteData _data; + + int u8(int at) => _check(at, 1, () => _data.getUint8(at)); + int u16(int at) => _check(at, 2, () => _data.getUint16(at)); + int u32(int at) => _check(at, 4, () => _data.getUint32(at)); + int u64(int at) => _check( + at, + 8, + () => + getPortableInt64(_data, at) ?? + (throw const UnsupportedVideoException()), + ); + + int _check(int at, int width, int Function() read) { + if (at < 0 || at + width > bytes.length) { + throw const UnsupportedVideoException(); + } + return read(); + } + + /// The boxes between [from] and [to]. + List<_Box> children(int from, int to) { + final out = <_Box>[]; + var at = from; + while (at < to) { + if (to - at < 8) throw const UnsupportedVideoException(); + var size = u32(at); + var header = 8; + final type = latin1.decode(bytes.sublist(at + 4, at + 8)); + if (size == 1) { + size = u64(at + 8); + header = 16; + } else if (size == 0) { + size = to - at; + } + if (size < header || size > to - at) { + throw const UnsupportedVideoException(); + } + out.add(_Box(type, at, at + header, at + size)); + at += size; + if (out.length > 4096) throw const UnsupportedVideoException(); + } + return out; + } + + _Box? first(_Box parent, String type) { + for (final box in children(parent.content, parent.end)) { + if (box.type == type) return box; + } + return null; + } + + _Box? path(_Box parent, List types) { + _Box? at = parent; + for (final type in types) { + if (at == null) return null; + at = first(at, type); + } + return at; + } + + /// A track's handler: `vide`, `soun`, or anything else. + String handler(_Box trak) { + final hdlr = path(trak, ['mdia', 'hdlr']); + if (hdlr == null) return ''; + // version and flags (4), pre_defined (4), then the type. + final at = hdlr.content + 8; + if (at + 4 > hdlr.end) throw const UnsupportedVideoException(); + return latin1.decode(bytes.sublist(at, at + 4)); + } +} + +/// Reads what a video says about itself, without decoding it. +abstract final class VideoProbe { + /// serv.pub takes files of at most 21 MiB. + static const maxBytes = 21 * 1024 * 1024; + + /// A short clip of a step; a camera asked for 60 s may give a few + /// frames more. + static const maxDuration = Duration(seconds: 61); + static const maxSide = 8192; + + static const _brands = { + 'isom', + 'iso2', + 'iso4', + 'iso5', + 'iso6', + 'mp41', + 'mp42', + 'avc1', + 'M4V ', + 'qt ', + }; + + /// Throws [UnsupportedVideoException] or [VideoTooLargeException]. + static VideoHeader probe(Uint8List bytes) { + if (bytes.length > maxBytes) throw const VideoTooLargeException(); + final boxes = _Boxes(bytes); + final top = boxes.children(0, bytes.length); + if (top.isEmpty || top.first.type != 'ftyp') { + throw const UnsupportedVideoException(); + } + final ftyp = top.first; + final brands = { + for (var at = ftyp.content; at + 4 <= ftyp.end; at += 4) + if (at != ftyp.content + 4) latin1.decode(bytes.sublist(at, at + 4)), + }; + if (brands.intersection(_brands).isEmpty) { + throw const UnsupportedVideoException(); + } + final moovs = top.where((b) => b.type == 'moov').toList(); + if (moovs.length != 1 || + !top.any((b) => b.type == 'mdat') || + top.any((b) => b.type == 'moof')) { + throw const UnsupportedVideoException(); + } + final moov = moovs.single; + final mvhd = + boxes.first(moov, 'mvhd') ?? (throw const UnsupportedVideoException()); + final v1 = boxes.u8(mvhd.content) == 1; + final timescale = boxes.u32(mvhd.content + (v1 ? 20 : 12)); + final length = v1 + ? boxes.u64(mvhd.content + 24) + : boxes.u32(mvhd.content + 16); + if (timescale == 0) throw const UnsupportedVideoException(); + // Past the limit before the conversion can overflow. + if (length ~/ timescale > maxDuration.inSeconds) { + throw const VideoTooLargeException(); + } + final duration = Duration(microseconds: length * 1000000 ~/ timescale); + for (final trak in boxes.children(moov.content, moov.end)) { + if (trak.type != 'trak' || boxes.handler(trak) != 'vide') continue; + final tkhd = + boxes.first(trak, 'tkhd') ?? + (throw const UnsupportedVideoException()); + final at = tkhd.content + (boxes.u8(tkhd.content) == 1 ? 88 : 76); + final width = boxes.u32(at) >> 16; + final height = boxes.u32(at + 4) >> 16; + return VideoHeader(VideoFormat.mp4, width, height, duration); + } + throw const UnsupportedVideoException(); + } +} + +/// Rewrites a video keeping only what plays it: the location, the date, +/// the device and every other note a phone writes into the file stay out. +/// +/// The rewrite keeps an allowlist of boxes and drops the rest, failing +/// closed: at the top `ftyp`, `moov` and `mdat`; in `moov` the header and +/// the video and sound tracks (a timed-metadata, text or other track is +/// dropped and its samples zeroed in `mdat`, since that is where some +/// cameras put the GPS track); in each track only what decoding needs, +/// with a data reference that points at the file itself. The creation and +/// modification times of the movie, its tracks and their media are set +/// to zero. Chunk offsets are moved to where the samples now are. +abstract final class VideoScrubber { + static const _moov = {'mvhd', 'trak'}; + static const _trak = {'tkhd', 'edts', 'mdia'}; + static const _edts = {'elst'}; + static const _mdia = {'mdhd', 'hdlr', 'minf'}; + static const _minf = {'vmhd', 'smhd', 'dinf', 'stbl'}; + static const _stbl = { + 'stsd', + 'stts', + 'ctts', + 'cslg', + 'stss', + 'stps', + 'sdtp', + 'stsc', + 'stsz', + 'stz2', + 'stco', + 'co64', + 'sgpd', + 'sbgp', + }; + + /// A `dinf` whose one reference is the file itself. + static final _selfDinf = Uint8List.fromList([ + 0, 0, 0, 36, ...latin1.encode('dinf'), // + 0, 0, 0, 28, ...latin1.encode('dref'), 0, 0, 0, 0, 0, 0, 0, 1, + 0, 0, 0, 12, ...latin1.encode('url '), 0, 0, 0, 1, + ]); + + /// Throws [UnsupportedVideoException] or [VideoTooLargeException]. + static Uint8List scrub(Uint8List bytes) { + VideoProbe.probe(bytes); + final boxes = _Boxes(bytes); + final top = boxes.children(0, bytes.length); + final moov = top.firstWhere((b) => b.type == 'moov'); + final mdats = [ + for (final box in top) + if (box.type == 'mdat') box, + ]; + + // The samples of dropped tracks, zeroed in the copies of mdat. + final zeroed = <(int, int)>[]; + final kept = {}; + for (final trak in boxes.children(moov.content, moov.end)) { + if (trak.type != 'trak') continue; + final handler = boxes.handler(trak); + if (handler == 'vide' || handler == 'soun') { + kept.add(trak.start); + } else { + zeroed.addAll(_chunks(boxes, trak)); + } + } + + // The new moov, with the offset tables noted to patch them once the + // file's new layout is known. + final tables = <(int at, _Box table)>[]; + final out = BytesBuilder(copy: false); + void copy(_Box box, Set allowed) { + final start = out.length; + out.add(Uint8List(8)); // size and type, written below + for (final child in boxes.children(box.content, box.end)) { + if (!allowed.contains(child.type)) continue; + if (box.type == 'moov' && + child.type == 'trak' && + !kept.contains(child.start)) { + continue; + } + switch (child.type) { + case 'trak': + copy(child, _trak); + case 'edts': + copy(child, _edts); + case 'mdia': + copy(child, _mdia); + case 'minf': + copy(child, _minf); + case 'stbl': + copy(child, _stbl); + case 'dinf': + out.add(_selfDinf); + case 'mvhd' || 'tkhd' || 'mdhd': + out.add(_timeless(boxes, child)); + case 'stco' || 'co64': + tables.add((out.length, child)); + out.add(_whole(bytes, child)); + default: + out.add(_whole(bytes, child)); + } + } + _header(out, start, box.type); + } + + copy(moov, _moov); + final newMoov = out.takeBytes(); + + // ftyp, moov, then each mdat (a 64-bit size kept as it was). + final ftyp = top.first; + final starts = <_Box, int>{}; + var at = ftyp.end - ftyp.start + newMoov.length; + for (final mdat in mdats) { + starts[mdat] = at; + at += mdat.end - mdat.start; + } + int moved(int offset) { + for (final mdat in mdats) { + if (offset >= mdat.content && offset <= mdat.end) { + return starts[mdat]! + (offset - mdat.start); + } + } + throw const UnsupportedVideoException(); + } + + final moovData = ByteData.sublistView(newMoov); + for (final (pos, table) in tables) { + final wide = table.type == 'co64'; + final count = moovData.getUint32(pos + 12); + final width = wide ? 8 : 4; + if (16 + count * width > table.end - table.start) { + throw const UnsupportedVideoException(); + } + for (var i = 0; i < count; i++) { + final entry = pos + 16 + i * width; + if (wide) { + final value = + getPortableInt64(moovData, entry) ?? + (throw const UnsupportedVideoException()); + setPortableInt64(moovData, entry, moved(value)); + } else { + final value = moved(moovData.getUint32(entry)); + if (value > 0xFFFFFFFF) throw const UnsupportedVideoException(); + moovData.setUint32(entry, value); + } + } + } + + final file = BytesBuilder(copy: false) + ..add(Uint8List.sublistView(bytes, ftyp.start, ftyp.end)) + ..add(newMoov); + for (final mdat in mdats) { + final copy = Uint8List.fromList( + Uint8List.sublistView(bytes, mdat.start, mdat.end), + ); + for (final (from, to) in zeroed) { + final a = (from - mdat.start).clamp( + mdat.content - mdat.start, + copy.length, + ); + final b = (to - mdat.start).clamp( + mdat.content - mdat.start, + copy.length, + ); + if (a < b) copy.fillRange(a, b, 0); + } + file.add(copy); + } + return file.takeBytes(); + } + + static Uint8List _whole(Uint8List bytes, _Box box) => + Uint8List.sublistView(bytes, box.start, box.end); + + /// Writes the size and type of the box that started at [start]. + static void _header(BytesBuilder out, int start, String type) { + final all = out.takeBytes(); + final data = ByteData.sublistView(all); + final size = all.length - start; + data.setUint32(start, size); + all.setRange(start + 4, start + 8, latin1.encode(type)); + out.add(all); + } + + /// A header box with its creation and modification times set to zero. + static Uint8List _timeless(_Boxes boxes, _Box box) { + final copy = Uint8List.fromList(_whole(boxes.bytes, box)); + final content = box.content - box.start; + final v1 = boxes.u8(box.content) == 1; + final width = v1 ? 16 : 8; + if (content + 4 + width > copy.length) { + throw const UnsupportedVideoException(); + } + copy.fillRange(content + 4, content + 4 + width, 0); + return copy; + } + + /// Where each chunk of [trak] is in the file: its offset and the sum of + /// its samples' sizes. + static List<(int, int)> _chunks(_Boxes boxes, _Box trak) { + final stbl = boxes.path(trak, ['mdia', 'minf', 'stbl']); + if (stbl == null) return const []; + final stco = boxes.first(stbl, 'stco'); + final co64 = boxes.first(stbl, 'co64'); + final stsc = boxes.first(stbl, 'stsc'); + final stsz = boxes.first(stbl, 'stsz'); + if ((stco == null && co64 == null) || stsc == null || stsz == null) { + throw const UnsupportedVideoException(); + } + final table = stco ?? co64!; + final wide = stco == null; + final chunks = boxes.u32(table.content + 4); + if (chunks > (table.end - table.content) ~/ 4) { + throw const UnsupportedVideoException(); + } + final offsets = [ + for (var i = 0; i < chunks; i++) + wide + ? boxes.u64(table.content + 8 + i * 8) + : boxes.u32(table.content + 8 + i * 4), + ]; + final runs = boxes.u32(stsc.content + 4); + if (runs > (stsc.end - stsc.content) ~/ 12) { + throw const UnsupportedVideoException(); + } + final uniform = boxes.u32(stsz.content + 4); + final samples = boxes.u32(stsz.content + 8); + if (uniform == 0 && samples > (stsz.end - stsz.content) ~/ 4) { + throw const UnsupportedVideoException(); + } + int sizeOf(int sample) => uniform != 0 + ? uniform + : sample < samples + ? boxes.u32(stsz.content + 12 + sample * 4) + : 0; + final out = <(int, int)>[]; + var sample = 0; + for (var r = 0; r < runs; r++) { + final first = boxes.u32(stsc.content + 8 + r * 12) - 1; + final perChunk = boxes.u32(stsc.content + 12 + r * 12); + final last = r + 1 < runs + ? boxes.u32(stsc.content + 8 + (r + 1) * 12) - 1 + : chunks; + if (first < 0 || last > chunks || first > last) { + throw const UnsupportedVideoException(); + } + for (var c = first; c < last; c++) { + var size = 0; + for (var s = 0; s < perChunk && sample < samples; s++) { + size += sizeOf(sample++); + } + out.add((offsets[c], offsets[c] + size)); + } + } + return out; + } +} diff --git a/packages/blob_storage_media/test/fixtures/video_back.mp4 b/packages/blob_storage_media/test/fixtures/video_back.mp4 new file mode 100644 index 0000000..2342976 Binary files /dev/null and b/packages/blob_storage_media/test/fixtures/video_back.mp4 differ diff --git a/packages/blob_storage_media/test/fixtures/video_front.mp4 b/packages/blob_storage_media/test/fixtures/video_front.mp4 new file mode 100644 index 0000000..3ff8be8 Binary files /dev/null and b/packages/blob_storage_media/test/fixtures/video_front.mp4 differ diff --git a/packages/blob_storage_media/test/fixtures/video_subtitled.mp4 b/packages/blob_storage_media/test/fixtures/video_subtitled.mp4 new file mode 100644 index 0000000..31b56c4 Binary files /dev/null and b/packages/blob_storage_media/test/fixtures/video_subtitled.mp4 differ diff --git a/packages/blob_storage_media/test/recorded_note_test.dart b/packages/blob_storage_media/test/recorded_note_test.dart index 88956dd..5b68313 100644 --- a/packages/blob_storage_media/test/recorded_note_test.dart +++ b/packages/blob_storage_media/test/recorded_note_test.dart @@ -217,6 +217,120 @@ void main() { ); }); + group('videos', () { + final recipe = SeedSchemas.recipeV1; + SchemaDefinition? recipes(SchemaId id) => id == recipe.id ? recipe : null; + final digest = ContentDigest.fromBytes(List.filled(32, 0xcd)); + KeyedVideo clip(String id, {ContentDigest? digest}) => KeyedVideo( + epoch: KeyEpoch(2), + metadata: VideoMetadata( + blob: SealedBlob( + id: BlobId(id), + keyId: SubkeyId.fromBytes(List.filled(SubkeyId.length, 7)), + plaintextLength: 900000, + digest: digest, + ), + info: VideoHeader( + VideoFormat.mp4, + 1080, + 1920, + const Duration(seconds: 42, milliseconds: 500), + ), + addedAt: later, + ), + ); + DynamicEntry dish(List videos) => valid( + DynamicEntry.create( + schema: recipe, + id: EntryId('fedcba9876543210fedcba9876543210'), + attributes: { + FieldKey('title'): const TextValue('Pane'), + FieldKey('steps'): StepsValue([ + for (final id in videos) + PreparationStep('Impasta', video: BlobId(id)), + PreparationStep('Inforna'), + ]), + }, + at: at, + ), + ); + + test('a step\'s video travels with the note, as version 6', () { + final note = RecordedNote.compose( + dish(['clip_1']), + clips: [clip('clip_1', digest: digest)], + ); + expect(note.videos.keys, [BlobId('clip_1')]); + expect(note.blobs.map((b) => b.id), [BlobId('clip_1')]); + + final wire = RecordedNoteCodec.encode(note); + expect(wire[0], 6); + final back = valid(RecordedNoteCodec.decode(wire, schemas: recipes)); + expect(back.videos, note.videos); + expect(back.videos.values.single.blob.digest, digest); + expect(back.entry.attributes, note.entry.attributes); + // Without a video the note keeps its older version. + expect(RecordedNoteCodec.encode(RecordedNote.of(dish([])))[0], 1); + }); + + test( + 'a video the note does not name is left out; one it names is needed', + () { + final edited = RecordedNote.compose( + dish(['clip_1']), + clips: [clip('clip_1')], + ).edited(dish([]), clips: [clip('clip_2')]); + expect(edited.videos, isEmpty); + expect( + RecordedNote.released( + before: RecordedNote.compose( + dish(['clip_1']), + clips: [clip('clip_1')], + ), + after: edited, + ), + {BlobId('clip_1')}, + ); + expect( + () => RecordedNote.compose(dish(['clip_1'])), + throwsArgumentError, + ); + }, + ); + + test('adversary: truncations, a missing or unnamed video are refused', () { + final wire = RecordedNoteCodec.encode( + RecordedNote.compose(dish(['clip_1']), clips: [clip('clip_1')]), + ); + for (var length = 0; length < wire.length; length++) { + expect( + () => RecordedNoteCodec.decode( + Uint8List.sublistView(wire, 0, length), + schemas: recipes, + ), + throwsA(isA()), + reason: '$length bytes', + ); + } + expect( + () => RecordedNoteCodec.decode([...wire, 0], schemas: recipes), + throwsA(isA()), + ); + // The same video section under a note whose steps name another. + final other = RecordedNoteCodec.encode( + RecordedNote.compose(dish(['clip_9']), clips: [clip('clip_9')]), + ); + final swapped = Uint8List.fromList([ + ...other.sublist(0, other.length - (wire.length - _body(wire))), + ...wire.sublist(_body(wire)), + ]); + expect( + () => RecordedNoteCodec.decode(swapped, schemas: recipes), + throwsA(isA()), + ); + }); + }); + group('trash', () { test('a note starts outside the trash', () { expect(RecordedNote.of(song()).trashedAt, isNull); @@ -489,3 +603,10 @@ void main() { }); }); } + +/// Where a version-6 note's flags start: after the version, the entry and +/// the recordings' count (none in these tests). +int _body(Uint8List wire) { + final data = ByteData.sublistView(wire); + return 1 + 4 + data.getUint32(1) + 2; +} diff --git a/packages/blob_storage_media/test/video_test.dart b/packages/blob_storage_media/test/video_test.dart new file mode 100644 index 0000000..e75dea9 --- /dev/null +++ b/packages/blob_storage_media/test/video_test.dart @@ -0,0 +1,226 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:blob_storage_media/blob_storage_media.dart'; +import 'package:identity_cryptography/identity_cryptography.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; +import 'package:test/test.dart'; + +import 'support.dart'; + +/// Clips made with ffmpeg (1 s, 64×48, H.264 and AAC) carrying a +/// location, a title, the encoder's name and a creation time: +/// `video_front.mp4` with moov before mdat (`+faststart`), +/// `video_back.mp4` the same streams with moov after mdat, and +/// `video_subtitled.mp4` with a text track whose one sample reads +/// «GPS 45.4642 9.1900 segreto», the way some cameras keep a GPS track. +Uint8List fixture(String name) => File('test/fixtures/$name').readAsBytesSync(); + +bool holds(Uint8List bytes, String text) => + latin1.decode(bytes, allowInvalid: true).contains(text); + +/// The boxes at the top of [bytes], by type. +List top(Uint8List bytes) { + final data = ByteData.sublistView(bytes); + final out = []; + for (var at = 0; at < bytes.length;) { + final size = data.getUint32(at); + out.add(latin1.decode(bytes.sublist(at + 4, at + 8))); + at += size == 0 ? bytes.length - at : size; + } + return out; +} + +void main() { + final front = fixture('video_front.mp4'); + final back = fixture('video_back.mp4'); + final subtitled = fixture('video_subtitled.mp4'); + + group('VideoProbe', () { + test('reads the size and the length from the boxes', () { + for (final clip in [front, back, subtitled]) { + final info = VideoProbe.probe(clip); + expect(info.format, VideoFormat.mp4); + expect((info.width, info.height), (64, 48)); + expect(info.duration, const Duration(seconds: 1)); + } + expect(VideoFormat.mp4.mimeType, 'video/mp4'); + }); + + test('refuses what is not a short MP4', () { + expect( + () => VideoProbe.probe(Uint8List.fromList(utf8.encode('ciao'))), + throwsA(isA()), + ); + expect( + () => VideoProbe.probe(Uint8List(VideoProbe.maxBytes + 1)), + throwsA(isA()), + ); + // Two minutes: the movie header's duration, patched. + final long = Uint8List.fromList(front); + final at = _find(long, 'mvhd') + 4; + final data = ByteData.sublistView(long); + final timescale = data.getUint32(at + 12); + data.setUint32(at + 16, timescale * 120); + expect( + () => VideoProbe.probe(long), + throwsA(isA()), + ); + // A fragmented file keeps its samples elsewhere. + final fragmented = Uint8List.fromList([ + ...front, + 0, 0, 0, 8, ...latin1.encode('moof'), // + ]); + expect( + () => VideoProbe.probe(fragmented), + throwsA(isA()), + ); + }); + + test('hostile bytes are only ever refused', () { + final random = Random(5); + for (var i = 0; i < 2000; i++) { + final bytes = Uint8List.fromList(front); + for (var j = 0; j < 1 + random.nextInt(4); j++) { + bytes[random.nextInt(2000)] = random.nextInt(256); + } + final cut = random.nextBool() + ? bytes + : Uint8List.sublistView(bytes, 0, random.nextInt(bytes.length)); + try { + VideoScrubber.scrub(cut); + } on UnsupportedVideoException { + // refused + } on VideoTooLargeException { + // refused + } + } + }); + }); + + group('VideoScrubber', () { + test('leaves out the location, the title, the encoder and the times', () { + for (final clip in [front, back, subtitled]) { + expect(holds(clip, 'Cucina di casa'), isTrue); + final clean = VideoScrubber.scrub(clip); + expect(holds(clean, 'Cucina di casa'), isFalse); + expect(holds(clean, 'Lavf'), isFalse); + expect(holds(clean, 'udta'), isFalse); + expect(holds(clean, 'loci'), isFalse); + expect(holds(clean, 'free'), isFalse); + expect(top(clean), ['ftyp', 'moov', 'mdat']); + for (final header in ['mvhd', 'tkhd', 'mdhd']) { + final at = _find(clean, header) + 4; + expect( + clean.sublist(at + 4, at + 12), + List.filled(8, 0), + reason: header, + ); + } + expect(VideoProbe.probe(clean), VideoProbe.probe(clip)); + } + }); + + test('a text track is dropped and its samples zeroed', () { + expect(holds(subtitled, 'segreto'), isTrue); + final clean = VideoScrubber.scrub(subtitled); + expect(holds(clean, 'segreto'), isFalse); + expect(holds(clean, '45.4642'), isFalse); + expect(holds(clean, 'sbtl') || holds(clean, 'text'), isFalse); + }); + + test('samples are where the offsets say, whatever the layout', () { + // The same streams, moov first or last: one clean file. + expect(VideoScrubber.scrub(front), VideoScrubber.scrub(back)); + final once = VideoScrubber.scrub(back); + expect(VideoScrubber.scrub(once), once); + }); + }); + + group('VideoStorage', () { + setUpAll(initSodium); + + late InMemoryBlobStore store; + late VideoStorage videos; + late SymmetricKey contentKey; + final at = DateTime.utc(2026, 11, 1, 11); + + setUp(() { + store = InMemoryBlobStore(); + videos = VideoStorage( + storage: EncryptedBlobStorage( + store: store, + encryptor: newEncryptor(), + subkeys: newSubkeys(), + hasher: newHasher(), + ), + ); + contentKey = newEncryptor().generateKey(); + addTearDown(contentKey.dispose); + }); + + test('seals a clean copy and opens it again', () async { + final sealed = await videos.seal( + subtitled, + id: BlobId('clip'), + contentKey: contentKey, + at: at, + ); + final clean = VideoScrubber.scrub(subtitled); + expect(sealed.info, VideoProbe.probe(subtitled)); + expect(sealed.blob.plaintextLength, clean.length); + expect(sealed.addedAt, at); + final opened = await videos.open(sealed, contentKey: contentKey); + expect(opened, clean); + expect(holds(opened, 'segreto'), isFalse); + expect(holds(store.committed[BlobId('clip')]!, 'ftyp'), isFalse); + }); + + test('refuses what is not a video, writing nothing', () async { + await expectLater( + videos.seal( + Uint8List.fromList(utf8.encode('')), + id: BlobId('svg'), + contentKey: contentKey, + at: at, + ), + throwsA(isA()), + ); + expect(store.committed, isEmpty); + expect(store.pending, isEmpty); + }); + + test('a video that is not the one described is never handed out', () async { + final sealed = await videos.seal( + front, + id: BlobId('clip'), + contentKey: contentKey, + at: at, + ); + final lying = VideoMetadata( + blob: sealed.blob, + info: VideoHeader(VideoFormat.mp4, 640, 480, sealed.info.duration), + addedAt: at, + ); + await expectLater( + videos.open(lying, contentKey: contentKey), + throwsA(isA()), + ); + }); + }); +} + +int _find(Uint8List bytes, String type) { + final target = latin1.encode(type); + for (var i = 0; i + 4 <= bytes.length; i++) { + if (bytes[i] == target[0] && + bytes[i + 1] == target[1] && + bytes[i + 2] == target[2] && + bytes[i + 3] == target[3]) { + return i; + } + } + throw StateError('no $type'); +} diff --git a/packages/publishing/lib/src/application/publisher.dart b/packages/publishing/lib/src/application/publisher.dart index 46245cc..3954089 100644 --- a/packages/publishing/lib/src/application/publisher.dart +++ b/packages/publishing/lib/src/application/publisher.dart @@ -114,7 +114,11 @@ final class Publisher { final published = await _withKey(book, (key) async { final uploaded = {}; try { - for (final blob in {...content.images, ...content.audio}) { + for (final blob in { + ...content.images, + ...content.audio, + ...content.videos, + }) { final prepared = await _media.prepare(blob); if (prepared == null) continue; final id = MediaId.random(_random); @@ -139,6 +143,13 @@ final class Publisher { layout: layout, ); await _gateway.putPage(key, book.name, slug, document.toJson()); + // A file the layout does not show (a step's video on a page of + // blocks) would stay on the site with nothing pointing at it. + await _deleteQuietly( + key, + book, + uploaded.values.where((id) => !document.media.contains(id)), + ); return PublishedPage( slug: slug, title: document.title, diff --git a/packages/publishing/lib/src/core/media.dart b/packages/publishing/lib/src/core/media.dart index 4047dc3..f9addd3 100644 --- a/packages/publishing/lib/src/core/media.dart +++ b/packages/publishing/lib/src/core/media.dart @@ -12,13 +12,18 @@ enum MediaKind { png('image/png'), webp('image/webp'), ogg('audio/ogg'), - webm('audio/webm'); + webm('audio/webm'), + + /// A recipe step's short clip, cleaned of its metadata on the device. + mp4('video/mp4'); const MediaKind(this.contentType); final String contentType; bool get isImage => this == jpeg || this == png || this == webp; + + bool get isVideo => this == mp4; } /// The name of one uploaded file on a site: random and new for every diff --git a/packages/publishing/lib/src/core/page_document.dart b/packages/publishing/lib/src/core/page_document.dart index ad5379b..73b6f1c 100644 --- a/packages/publishing/lib/src/core/page_document.dart +++ b/packages/publishing/lib/src/core/page_document.dart @@ -568,8 +568,12 @@ final class _RecipeDraft { PageComposer._markdown(step.text, _media).trim(), PageRecipe.maxStep, ); - if (text.trim().isEmpty && kept.isEmpty) continue; - _steps.add(RecipeStep(text, kept)); + final video = switch (step.video) { + final blob? => _media[blob], + null => null, + }; + if (text.trim().isEmpty && kept.isEmpty && video == null) continue; + _steps.add(RecipeStep(text, kept, video)); } default: return false; diff --git a/packages/publishing/lib/src/core/page_recipe.dart b/packages/publishing/lib/src/core/page_recipe.dart index 8786219..ae45618 100644 --- a/packages/publishing/lib/src/core/page_recipe.dart +++ b/packages/publishing/lib/src/core/page_recipe.dart @@ -51,18 +51,22 @@ final class RecipeIngredient { }; } -/// One step: Markdown, and its pictures. +/// One step: Markdown, its pictures and its short video. @immutable final class RecipeStep { - RecipeStep(this.text, [List pictures = const []]) + RecipeStep(this.text, [List pictures = const [], this.video]) : pictures = List.unmodifiable(pictures); final String text; final List pictures; + /// The uploaded, cleaned copy of the step's video. + final MediaId? video; + Map toJson() => { 'text': text, 'pictures': [for (final p in pictures) p.toJson()], + 'video': ?video?.value, }; } @@ -133,7 +137,10 @@ final class PageRecipe { /// Every file the recipe shows. Iterable get media => [ for (final p in cover) p.media, - for (final step in steps) ...[for (final p in step.pictures) p.media], + for (final step in steps) ...[ + for (final p in step.pictures) p.media, + ?step.video, + ], ]; Map toJson() => { diff --git a/packages/publishing/lib/src/core/publication_policy.dart b/packages/publishing/lib/src/core/publication_policy.dart index b8cc247..2d6b48f 100644 --- a/packages/publishing/lib/src/core/publication_policy.dart +++ b/packages/publishing/lib/src/core/publication_policy.dart @@ -16,9 +16,11 @@ final class PublicationContent { required Map fields, required List images, required List audio, + required List videos, }) : fields = Map.unmodifiable(fields), images = List.unmodifiable(images), - audio = List.unmodifiable(audio); + audio = List.unmodifiable(audio), + videos = List.unmodifiable(videos); /// One safe line, possibly empty (the app then shows its own words). final String title; @@ -32,6 +34,9 @@ final class PublicationContent { /// clean copy of each (pictures re-encoded without metadata). final List images; final List audio; + + /// The steps' videos: the app uploads a copy cleaned of its metadata. + final List videos; } /// The rules on what may leave the vault when a note is published. Publishing @@ -54,8 +59,8 @@ abstract final class PublicationPolicy { /// become links to their pages when [published] has them, plain text /// otherwise, so no id or page of a private note leaks. Without /// [includePictures] pictures in the text become their caption and - /// pictures among the attachments and the steps of a recipe are left - /// out. + /// pictures among the attachments and the pictures and videos of a + /// recipe's steps are left out. static PublicationContent compose({ required DynamicEntry entry, required SchemaDefinition schema, @@ -73,6 +78,7 @@ abstract final class PublicationPolicy { final out = {}; final images = {}; final audio = {}; + final videos = {}; String? title; for (final field in schema.fields) { if (!fields.contains(field.key)) continue; @@ -94,6 +100,7 @@ abstract final class PublicationPolicy { published, includePictures, images, + videos, ), _ => value, }; @@ -111,6 +118,7 @@ abstract final class PublicationPolicy { fields: out, images: images.toList(), audio: audio.toList(), + videos: videos.toList(), ); } @@ -154,20 +162,23 @@ abstract final class PublicationPolicy { /// Steps with their text cleaned like any text, a picture written in it /// always made its caption (a step's pictures are its own list), and - /// that list kept only with [includePictures]. + /// that list and the step's video kept only with [includePictures]. static StepsValue? _steps( List steps, Map published, bool includePictures, Set images, + Set videos, ) { final kept = []; for (final step in steps) { final pictures = includePictures ? step.pictures : []; + final video = includePictures ? step.video : null; images.addAll(pictures.map((p) => p.blob)); + if (video != null) videos.add(video); final text = _pictures(_links(step.text, published), false, images); - if (text.trim().isEmpty && pictures.isEmpty) continue; - kept.add(PreparationStep(text, pictures: pictures)); + if (text.trim().isEmpty && pictures.isEmpty && video == null) continue; + kept.add(PreparationStep(text, pictures: pictures, video: video)); } return kept.isEmpty ? null : StepsValue(kept); } diff --git a/packages/publishing/test/publisher_test.dart b/packages/publishing/test/publisher_test.dart index bb9a578..d6f5d45 100644 --- a/packages/publishing/test/publisher_test.dart +++ b/packages/publishing/test/publisher_test.dart @@ -363,6 +363,36 @@ void main() { expect((sent['ingredients']! as List).single, containsPair('one', 'g')); }); + test('a video the layout does not show is not left on the site', () async { + await publisher.claim(name, settings); + final clip = BlobId('c' * 32); + media.ready[clip] = PreparedMedia(MediaKind.mp4, Uint8List(16)); + final recipe = SeedSchemas.recipeV1; + final e = entry(recipe, { + 'title': const TextValue('Pane'), + 'steps': StepsValue([PreparationStep('Impasta', video: clip)]), + }); + Future publishAs(PublicationLayout layout) => publisher.publish( + entry: e.id, + content: PublicationPolicy.compose( + entry: e, + schema: recipe, + fields: keys_(['title', 'steps']), + ), + schema: recipe, + labelOf: labelOf, + describe: describe, + layout: layout, + ); + await publishAs(PublicationLayout.essay); + expect(server.files, isEmpty); + await publishAs(PublicationLayout.recipe); + expect(server.files.values, [MediaKind.mp4]); + final sent = server.pages['pane']!['recipe']! as Map; + final step = (sent['steps']! as List).single as Map; + expect(step['video'], server.files.keys.single); + }); + test('two notes with one title get two addresses', () async { await publisher.claim(name, settings); await publish('# Il faro\n\nA.'); diff --git a/packages/publishing/test/recipe_layout_test.dart b/packages/publishing/test/recipe_layout_test.dart index a9059b5..ece808d 100644 --- a/packages/publishing/test/recipe_layout_test.dart +++ b/packages/publishing/test/recipe_layout_test.dart @@ -15,10 +15,12 @@ void main() { final second = blob('b'); final stepPicture = blob('c'); final notUploaded = blob('d'); + final clip = blob('e'); final uploaded = { cover: copy('A'), second: copy('B'), stepPicture: copy('C'), + clip: copy('E'), }; final values = { @@ -58,7 +60,7 @@ void main() { ImageAttachment(notUploaded), ], ), - PreparationStep('Inforna a 180°.'), + PreparationStep('Inforna a 180°.', video: clip), ]), 'prep_time': NumberValue(40), 'cook_time': NumberValue(45), @@ -172,7 +174,9 @@ void main() { ]); expect(steps.first.pictures.map((p) => p.media), [copy('C')]); expect(steps.first.pictures.single.caption, 'Dorate'); - expect(page.media, [copy('A'), copy('B'), copy('C')]); + expect(steps.last.video, copy('E')); + expect(steps.first.video, isNull); + expect(page.media, [copy('A'), copy('B'), copy('C'), copy('E')]); }); test('the other fields stay blocks, the links among the photos too', () { @@ -186,6 +190,25 @@ void main() { expect((blocks.last as TextBlock).text, '180'); }); + test('without pictures, a step\'s video stays home too', () { + final content = PublicationPolicy.compose( + entry: entry(recipe, values), + schema: recipe, + fields: keys(values.keys), + includePictures: false, + ); + expect(content.videos, isEmpty); + expect(content.images, isEmpty); + expect( + PublicationPolicy.compose( + entry: entry(recipe, values), + schema: recipe, + fields: keys(values.keys), + ).videos, + [clip], + ); + }); + test('only the fields the person chose', () { final page = compose(fields: {'title', 'ingredients'}); final r = page.recipe!; diff --git a/packages/schema_dynamic_content/lib/src/core/entry_codec.dart b/packages/schema_dynamic_content/lib/src/core/entry_codec.dart index eb65f20..0f39f5a 100644 --- a/packages/schema_dynamic_content/lib/src/core/entry_codec.dart +++ b/packages/schema_dynamic_content/lib/src/core/entry_codec.dart @@ -174,8 +174,9 @@ abstract final class EntryCodec { ], ], }, - // [text, blob, caption, blob, caption, ...]: flat, so a step stays - // within the nesting the decoder allows. + // [text, blob, caption, blob, caption, ..., video?]: flat, so a step + // stays within the nesting the decoder allows; an odd one out at the + // end is the step's video. StepsValue(:final steps) => { 'kind': 'steps', 'value': [ @@ -186,6 +187,7 @@ abstract final class EntryCodec { picture.blob.value, picture.caption, ], + ?step.video?.value, ], ], }, @@ -266,23 +268,29 @@ abstract final class EntryCodec { 'steps' => StepsValue([ for (final step in json.list('value')) switch (step) { - [final String text, ...final pictures] - when pictures.length.isEven => - PreparationStep( - text, - pictures: [ - for (var i = 0; i < pictures.length; i += 2) - switch ((pictures[i], pictures[i + 1])) { - (final String blob, final String caption) => - ImageAttachment(BlobId(blob), caption: caption), + [final String text, ...final rest] => PreparationStep( + text, + pictures: [ + for (var i = 0; i + 1 < rest.length; i += 2) + switch ((rest[i], rest[i + 1])) { + (final String blob, final String caption) => + ImageAttachment(BlobId(blob), caption: caption), + _ => throw const EntryFormatException( + 'a step picture is a blob and a caption', + ), + }, + ], + video: rest.length.isOdd + ? switch (rest.last) { + final String blob => BlobId(blob), _ => throw const EntryFormatException( - 'a step picture is a blob and a caption', + 'a step video is a blob', ), - }, - ], - ), + } + : null, + ), _ => throw const EntryFormatException( - 'a step is [text, blob, caption, ...]', + 'a step is [text, blob, caption, ..., video]', ), }, ]), diff --git a/packages/schema_dynamic_content/lib/src/core/field_type.dart b/packages/schema_dynamic_content/lib/src/core/field_type.dart index 0c288f5..351fedf 100644 --- a/packages/schema_dynamic_content/lib/src/core/field_type.dart +++ b/packages/schema_dynamic_content/lib/src/core/field_type.dart @@ -433,9 +433,9 @@ final class IngredientsFieldType extends FieldType { int get hashCode => Object.hash(IngredientsFieldType, maxItems); } -/// The steps of a preparation ([StepsValue]): Markdown and pictures. The -/// pictures of all the steps are bounded together, like the attachments -/// of a page, and each appears once. +/// The steps of a preparation ([StepsValue]): Markdown, pictures and a +/// short video each. The pictures of all the steps are bounded together, +/// like the attachments of a page, and each blob appears once. final class StepsFieldType extends FieldType { StepsFieldType({this.maxItems = 55}) { _requireRange(maxItems > 0 && maxItems <= maxAllowedItems); @@ -453,6 +453,7 @@ final class StepsFieldType extends FieldType { if (value is! StepsValue) return const [ViolationCode.typeMismatch]; final steps = value.steps; final pictures = value.pictures.toList(); + final blobs = [...pictures, ...value.videos]; return [ if (steps.isEmpty) ViolationCode.missingRequired, if (steps.length > maxItems || @@ -460,13 +461,15 @@ final class StepsFieldType extends FieldType { steps.any((step) => step.pictures.length > maxPicturesPerStep)) ViolationCode.tooManyItems, if (steps.any( - (step) => step.text.trim().isEmpty && step.pictures.isEmpty, + (step) => + step.text.trim().isEmpty && + step.pictures.isEmpty && + step.video == null, )) ViolationCode.emptyItem, if (steps.any((step) => _length(step.text) > maxText)) ViolationCode.tooLong, - if (pictures.toSet().length != pictures.length) - ViolationCode.duplicateItem, + if (blobs.toSet().length != blobs.length) ViolationCode.duplicateItem, ]; } diff --git a/packages/schema_dynamic_content/lib/src/core/field_value.dart b/packages/schema_dynamic_content/lib/src/core/field_value.dart index 349fe99..02013c5 100644 --- a/packages/schema_dynamic_content/lib/src/core/field_value.dart +++ b/packages/schema_dynamic_content/lib/src/core/field_value.dart @@ -345,27 +345,38 @@ final class IngredientsValue extends FieldValue { String toString() => 'IngredientsValue(${items.length} items)'; } -/// One step of a preparation: what to do, in Markdown, and pictures of it. +/// One step of a preparation: what to do, in Markdown, pictures of it and +/// at most one short [video] (a blob of its own, like a recording). @immutable final class PreparationStep { - PreparationStep(this.text, {List pictures = const []}) - : pictures = List.unmodifiable(pictures); + PreparationStep( + this.text, { + List pictures = const [], + this.video, + }) : pictures = List.unmodifiable(pictures); final String text; final List pictures; + final BlobId? video; + + /// The same step with [video] in place of its own (null: none). + PreparationStep withVideo(BlobId? video) => + PreparationStep(text, pictures: pictures, video: video); @override bool operator ==(Object other) => other is PreparationStep && other.text == text && + other.video == video && listEquals(other.pictures, pictures); @override - int get hashCode => Object.hash(text, Object.hashAll(pictures)); + int get hashCode => Object.hash(text, video, Object.hashAll(pictures)); @override String toString() => - 'PreparationStep(${text.length} chars, ${pictures.length} pictures)'; + 'PreparationStep(${text.length} chars, ${pictures.length} pictures' + '${video == null ? '' : ', a video'})'; } /// The steps of a preparation, in order. @@ -380,6 +391,16 @@ final class StepsValue extends FieldValue { for (final picture in step.pictures) picture.blob, ]; + /// Every step's video, in order. + Iterable get videos => [for (final step in steps) ?step.video]; + + /// The videos every steps field of [entry] holds, in order and each + /// once: blobs the note needs beside it, like its pictures. + static List videosOf(DynamicEntry entry) => { + for (final value in entry.attributes.values) + if (value is StepsValue) ...value.videos, + }.toList(); + @override bool operator ==(Object other) => other is StepsValue && listEquals(other.steps, steps); diff --git a/packages/schema_dynamic_content/test/recipe_test.dart b/packages/schema_dynamic_content/test/recipe_test.dart index 39b6622..539b62f 100644 --- a/packages/schema_dynamic_content/test/recipe_test.dart +++ b/packages/schema_dynamic_content/test/recipe_test.dart @@ -180,6 +180,29 @@ void main() { expect(roomy.check(StepsValue(steps)), [ViolationCode.tooManyItems]); }); + test('a step may hold a short video, even alone', () { + final clip = BlobId('v' * 32); + expect( + type.check(StepsValue([PreparationStep('', video: clip)])), + isEmpty, + ); + expect( + StepsValue([PreparationStep('a', video: clip), PreparationStep('b')]) + .videos, + [clip], + ); + // A blob is a picture or a video, once. + expect( + type.check( + StepsValue([ + PreparationStep('a', pictures: [ImageAttachment(stepPhoto)]), + PreparationStep('b', video: stepPhoto), + ]), + ), + [ViolationCode.duplicateItem], + ); + }); + test('a picture appears once across all the steps', () { expect( type.check( @@ -249,7 +272,7 @@ void main() { 'Friggi le **melanzane**.', pictures: [ImageAttachment(stepPhoto, caption: 'Dorate')], ), - PreparationStep('Inforna per 40 minuti.'), + PreparationStep('Inforna per 40 minuti.', video: BlobId('v' * 32)), ]), 'prep_time': NumberValue(30), 'cook_time': NumberValue(60), @@ -281,6 +304,7 @@ void main() { ); expect(back.attributes, full.attributes); + expect(StepsValue.videosOf(back), [BlobId('v' * 32)]); }); test('survives the schema codec unchanged', () { @@ -447,7 +471,10 @@ void main() { test('malformed steps are a format error', () { for (final step in [ [], - ['Taglia', 'b' * 32], + // An odd one out at the end is a video: a blob id, nothing else. + ['Taglia', 7], + ['Taglia', 'not a blob id!'], + ['Taglia', 'b' * 32, 'Dorate', 7], ['Taglia', 7, ''], ['Taglia', 'not a blob id!', ''], [7], diff --git a/pubspec.lock b/pubspec.lock index 8c6822b..5c5ff64 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -978,6 +978,46 @@ packages: url: "https://pub.dev" source: hosted version: "2.4.3" + video_player: + dependency: transitive + description: + name: video_player + sha256: "07ae1e03f2d4c8e2e9a75ee678f90acbc4506d4458a9c628512d119a1eee5754" + url: "https://pub.dev" + source: hosted + version: "2.14.1" + video_player_android: + dependency: transitive + description: + name: video_player_android + sha256: d27054dea34d748a44f06d433a57005d2aac69944485b0abbaed3303dbcfa3f1 + url: "https://pub.dev" + source: hosted + version: "2.12.2" + video_player_avfoundation: + dependency: transitive + description: + name: video_player_avfoundation + sha256: "7d620d8c69d00c158a5c57bf3d2a051833b547631203ff724664fbf301024bc1" + url: "https://pub.dev" + source: hosted + version: "2.12.3" + video_player_platform_interface: + dependency: transitive + description: + name: video_player_platform_interface + sha256: "92c0fbabe20c788e71fd10d26cea998d0d253282e65d145aed0818731cf593ce" + url: "https://pub.dev" + source: hosted + version: "6.9.0" + video_player_web: + dependency: transitive + description: + name: video_player_web + sha256: "9f3c00be2ef9b76a95d94ac5119fb843dca6f2c69e6c9968f6f2b6c9e7afbdeb" + url: "https://pub.dev" + source: hosted + version: "2.4.0" vm_service: dependency: transitive description: diff --git a/server/crates/publish/src/cookbook.rs b/server/crates/publish/src/cookbook.rs index 4d7a9c5..a018b41 100644 --- a/server/crates/publish/src/cookbook.rs +++ b/server/crates/publish/src/cookbook.rs @@ -681,7 +681,17 @@ pub fn recipe_page( .map(|p| format!("\"{}\"", p.media, escape(&p.caption))) .collect(); let pictures = if pictures.is_empty() { pictures } else { format!("
{pictures}
") }; - out.push_str(&format!("
  • {}{pictures}
  • ", markdown(&step.text, site, uploaded))); + // No autoplay, nothing loaded before it is asked for but its + // first frame's size: the page stays light. + let video = match &step.video { + Some(id) if uploaded(id) => { + format!( + "" + ) + } + _ => String::new(), + }; + out.push_str(&format!("
  • {}{pictures}{video}
  • ", markdown(&step.text, site, uploaded))); } out.push_str("\n"); } @@ -788,6 +798,7 @@ background:var(--tint,var(--bg));color:var(--cat,var(--accent));text-decoration: .steps li p:last-child{{margin-bottom:0}}\n\ .pics{{display:grid;grid-template-columns:61.8fr 38.2fr;gap:{xs}px;margin-top:{s}px}}\ .pics img{{aspect-ratio:{PHI:.3}/1;object-fit:cover;margin:0}}\n\ +.clip{{display:block;width:100%;max-height:610px;margin-top:{s}px;border-radius:{xs}px;background:var(--surface)}}\n\ .notes{{margin-top:{xl}px}}\n\ .more{{margin-top:{xxl}px;padding-top:{xl}px;border-top:1px solid var(--surface)}}\n\ .back{{display:inline-block;margin-top:{l}px;font-weight:600;color:var(--cat,var(--accent))}}\n\ @@ -933,6 +944,22 @@ mod tests { assert_eq!(category_page(SITE, &settings::sample(), &categories(), &entries(), "x", "1", &|_| true), None); } + #[test] + fn a_steps_video_plays_only_when_asked_and_only_if_uploaded() { + let mut r = recipe::sample(); + r.steps[1].video = Some("VVVVVVVVVVVVVVVV".into()); + let page = recipe_page_of(r.clone()); + let html = recipe_page(SITE, "p", &settings::sample(), &page, &r, &categories(), &[], None, "1", &|_| true); + assert!(html.contains( + "" + )); + assert!(!html.contains("autoplay")); + let missing = recipe_page(SITE, "p", &settings::sample(), &page, &r, &categories(), &[], None, "1", &|id| { + id != "VVVVVVVVVVVVVVVV" + }); + assert!(!missing.contains(", + /// A short clip (MP4, at most a minute), by its media id. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub video: Option, } /// The app's limits (`IngredientsFieldType`, `StepsFieldType`, recipe v1). @@ -170,6 +173,7 @@ impl Recipe { let mut out: Vec = self.cover.iter().map(|p| p.media.clone()).collect(); for step in &self.steps { out.extend(step.pictures.iter().map(|p| p.media.clone())); + out.extend(step.video.iter().cloned()); out.extend(crate::render::images_in(&step.text)); } out @@ -254,7 +258,10 @@ impl Ingredient { impl Step { fn check(&self) -> Result<(), Invalid> { - if self.text.trim().is_empty() && self.pictures.is_empty() { + if self.video.as_deref().is_some_and(|id| !media_id(id)) { + return Err(Invalid::Media); + } + if self.text.trim().is_empty() && self.pictures.is_empty() && self.video.is_none() { return Err(Invalid::Item); } if !safe_text(&self.text, MAX_STEP) || self.pictures.len() > MAX_STEP_PICTURES { @@ -423,8 +430,9 @@ pub(crate) fn sample() -> Recipe { Step { text: "Taglia le melanzane e lasciale scolare **30 minuti**.".into(), pictures: vec![Picture { media: "DDDDDDDDDDDDDDDD".into(), caption: "Fette".into() }], + video: None, }, - Step { text: "Inforna a 180 °C per 45 minuti.".into(), pictures: vec![] }, + Step { text: "Inforna a 180 °C per 45 minuti.".into(), pictures: vec![], video: None }, ], tags: vec!["estate".into()], } @@ -458,7 +466,14 @@ mod tests { assert_eq!(with(&|r| r.methods.push(" ".into())), Err(Invalid::Item)); assert_eq!(with(&|r| r.cover[0].media = "../x".into()), Err(Invalid::Media)); assert_eq!(with(&|r| r.steps[0].pictures[0].media = "x".into()), Err(Invalid::Media)); - assert_eq!(with(&|r| r.steps.push(Step { text: " ".into(), pictures: vec![] })), Err(Invalid::Item)); + assert_eq!( + with(&|r| r.steps.push(Step { text: " ".into(), pictures: vec![], video: None })), + Err(Invalid::Item) + ); + // A step may be only its video, a media id like any other. + let clip = |id: &str| Step { text: String::new(), pictures: vec![], video: Some(id.into()) }; + assert_eq!(with(&|r| r.steps.push(clip("VVVVVVVVVVVVVVVV"))), Ok(())); + assert_eq!(with(&|r| r.steps.push(clip("../../etc"))), Err(Invalid::Media)); assert_eq!(with(&|r| r.steps[0].text = "a\rb".into()), Err(Invalid::Text)); assert_eq!(with(&|r| r.ingredients = vec![sample().ingredients[0].clone(); 234]), Err(Invalid::Item)); for bad in [f64::NAN, f64::INFINITY, 0.0, -1.0, 1e7] { @@ -472,7 +487,7 @@ mod tests { } let many = vec![Picture { media: "DDDDDDDDDDDDDDDD".into(), caption: String::new() }; 8]; assert_eq!( - with(&|r| r.steps = vec![Step { text: "x".into(), pictures: many.clone() }; 12]), + with(&|r| r.steps = vec![Step { text: "x".into(), pictures: many.clone(), video: None }; 12]), Err(Invalid::Item) ); } diff --git a/server/crates/publish/src/site.rs b/server/crates/publish/src/site.rs index e5ad714..3b65575 100644 --- a/server/crates/publish/src/site.rs +++ b/server/crates/publish/src/site.rs @@ -98,6 +98,8 @@ pub enum MediaType { Ogg, /// Recordings made in a browser (Opus in WebM). Webm, + /// A recipe step's short clip, cleaned of its metadata by the app. + Mp4, } impl MediaType { @@ -108,6 +110,7 @@ impl MediaType { "webp" => Some(Self::Webp), "ogg" => Some(Self::Ogg), "webm" => Some(Self::Webm), + "mp4" => Some(Self::Mp4), _ => None, } } @@ -119,6 +122,7 @@ impl MediaType { Self::Webp => "webp", Self::Ogg => "ogg", Self::Webm => "webm", + Self::Mp4 => "mp4", } } @@ -129,6 +133,7 @@ impl MediaType { Self::Webp => "image/webp", Self::Ogg => "audio/ogg", Self::Webm => "audio/webm", + Self::Mp4 => "video/mp4", } } @@ -141,6 +146,8 @@ impl MediaType { Self::Ogg => bytes.starts_with(b"OggS"), // The EBML header every Matroska file opens with. Self::Webm => bytes.starts_with(&[0x1A, 0x45, 0xDF, 0xA3]), + // The file type box an MP4 or QuickTime file opens with. + Self::Mp4 => bytes.len() >= 12 && &bytes[4..8] == b"ftyp", } } } diff --git a/server/crates/publish/tests/app_pages.rs b/server/crates/publish/tests/app_pages.rs index 3b81fee..858cc3d 100644 --- a/server/crates/publish/tests/app_pages.rs +++ b/server/crates/publish/tests/app_pages.rs @@ -21,6 +21,8 @@ fn the_apps_recipe_is_a_valid_page() { assert_eq!(recipe.cover.len(), 2); assert_eq!(recipe.steps.len(), 2); assert_eq!(page.blocks.len(), 2); + assert_eq!(recipe.steps[1].video.as_deref(), Some("EEEEEEEEEEEEEEEEEEEEEE")); + assert!(page.media().contains(&"EEEEEEEEEEEEEEEEEEEEEE".to_owned())); } #[test] diff --git a/server/crates/publish/tests/fixtures/app_recipe.json b/server/crates/publish/tests/fixtures/app_recipe.json index c89519c..bb231ba 100644 --- a/server/crates/publish/tests/fixtures/app_recipe.json +++ b/server/crates/publish/tests/fixtures/app_recipe.json @@ -85,7 +85,8 @@ }, { "text": "Inforna a 180°.", - "pictures": [] + "pictures": [], + "video": "EEEEEEEEEEEEEEEEEEEEEE" } ], "tags": [ diff --git a/server/crates/publish/tests/site.rs b/server/crates/publish/tests/site.rs index 3930df9..76244a5 100644 --- a/server/crates/publish/tests/site.rs +++ b/server/crates/publish/tests/site.rs @@ -191,6 +191,10 @@ fn media_types_by_their_first_bytes() { assert!(!MediaType::Png.matches(b"