Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified .claude/private/CLAUDE.md
Binary file not shown.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
4 changes: 4 additions & 0 deletions apps/modusnote/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,9 @@
<action android:name="android.intent.action.VIEW"/>
<data android:scheme="http"/>
</intent>
<!-- A step's short video is recorded by the camera app. -->
<intent>
<action android:name="android.media.action.VIDEO_CAPTURE"/>
</intent>
</queries>
</manifest>
4 changes: 2 additions & 2 deletions apps/modusnote/ios/Runner/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
<key>NSMicrophoneUsageDescription</key>
<string>Modus Notes records audio notes, song sketches and dream logs. Recordings are encrypted on this device before they are saved.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Modus Notes adds the pictures you choose to your pages. Each picture is encrypted on this device before it is saved.</string>
<string>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.</string>
<key>NSCameraUsageDescription</key>
<string>Modus Notes does not use the camera; pictures are chosen from your photos.</string>
<string>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.</string>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
Expand Down
47 changes: 46 additions & 1 deletion apps/modusnote/lib/attachments/note_images.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,41 @@ abstract interface class ImageChooser {
Future<Uint8List?> 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<Uint8List?> 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 {
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.
final EncryptedBlobStorage blobs;
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<void> Function(SealedBlob blob)? _ensureLocal;
final DateTime Function() _clock;
final Random _random;
Expand Down Expand Up @@ -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<KeyedVideo?> 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<Uint8List> 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(
Expand Down
12 changes: 12 additions & 0 deletions apps/modusnote/lib/attachments/playable_video.dart
Original file line number Diff line number Diff line change
@@ -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';
53 changes: 53 additions & 0 deletions apps/modusnote/lib/attachments/playable_video_io.dart
Original file line number Diff line number Diff line change
@@ -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> 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<void> 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<Directory> _folder() async => Directory(
'${(await getTemporaryDirectory()).path}${Platform.pathSeparator}videos',
);

final class PlayableVideo {
PlayableVideo._(this.controller, this._file);

final VideoPlayerController controller;
final File _file;

Future<void> 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.
}
}
}
31 changes: 31 additions & 0 deletions apps/modusnote/lib/attachments/playable_video_web.dart
Original file line number Diff line number Diff line change
@@ -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> 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<void> sweepPlayableVideos() async {}

final class PlayableVideo {
PlayableVideo._(this.controller, this._url);

final VideoPlayerController controller;
final String _url;

Future<void> release() async {
await controller.dispose();
web.URL.revokeObjectURL(_url);
}
}
69 changes: 43 additions & 26 deletions apps/modusnote/lib/bootstrap/browser_image_chooser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8List?> choose() async {
final input = web.HTMLInputElement()
..type = 'file'
..accept = [for (final f in ImageFormat.values) f.mimeType].join(',');
final picked = Completer<web.File?>();
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<Uint8List?> 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<Uint8List?> 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<Uint8List?> _pick(String accept, int max, {bool video = false}) async {
final input = web.HTMLInputElement()
..type = 'file'
..accept = accept;
final picked = Completer<web.File?>();
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());
}
24 changes: 24 additions & 0 deletions apps/modusnote/lib/bootstrap/gallery_image_chooser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uint8List?> 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);
}
}
}
19 changes: 13 additions & 6 deletions apps/modusnote/lib/bootstrap/home_native.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:io';
import 'dart:ui' show PlatformDispatcher;

Expand All @@ -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';
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions apps/modusnote/lib/bootstrap/home_web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ VaultGate _gate({
blobs: blobs,
engine: engine,
chooser: BrowserImageChooser(),
videoChooser: BrowserVideoChooser(),
ensureLocal: ensureLocal,
),
playbackFor: (engine, ensureLocal) => NotePlayback(
Expand Down
18 changes: 18 additions & 0 deletions apps/modusnote/lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
Expand Up @@ -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."
},
Expand Down
11 changes: 11 additions & 0 deletions apps/modusnote/lib/l10n/app_it.arb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading