Keep each photo once in the account's private entity data, shared by every app
Diary and Photos keep their photos as records of the account's entity data (Daochi docs/entity-data.md): entity.photos.<sha256>, synced as private.entity.v1.photos in Inbe's own signed v6 sync and sealed in Daochi's record profile with the account's photos key, the same bytes libsodium writes. A photo's bytes travel as sealed chunks of at most 8 MiB at /api/v1/blobs/entity/, so the same picture is stored once per node for every app of the account. Photos released versions kept move there by themselves: library photos once their bytes are on the device, and Diary files that an entry includes, named and dated as before. An old copy goes only after the sync node confirmed the photo's record and chunks and they came back whole; then the old records name the photo and keep every field for released versions, which read them through 2027-10-24, the Diary file leaves the device, hex chunks shrink, and the old copies are deleted from each node. Any failure keeps the old copy for a later pass, and a delegate device moves nothing.
This commit is contained in:
1 parent
07486d6d54
commit
14c57367d5
45 files changed
+4059
-804
No files matched your search
@@ -5,6 +5,7 @@
|
||||
- Practice illustrations keep clean, smooth edges on desktop, without dark seams across the Sun Salutation guide.
|
||||
- Smoother on phones: the How to guides, still screens and paused practices draw far less.
|
||||
- Apps and practices use the new ZX format and update themselves after installing.
|
||||
- Diary and Photos keep each photo once for your account, privately, shared by all your apps. Photos saved before move there by themselves, and their old copies are removed only once the new ones are safely stored.
|
||||
|
||||
## [2.1.44] - 2026-10-23
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
AchievementPhotoBackfill :: (offset: s32) -> s32 {
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(),
|
||||
"SELECT value FROM settings WHERE user_id=?1 AND key GLOB 'cell.media.*' AND length(key)=75 ORDER BY key LIMIT 128 OFFSET ?2",
|
||||
"SELECT value FROM settings WHERE user_id=?1 AND ((key GLOB 'entity.photos.*' AND length(key)=78) OR (key GLOB 'cell.media.*' AND length(key)=75 AND NOT EXISTS (SELECT 1 FROM settings e WHERE e.user_id=?1 AND e.key='entity.photos.'||substr(settings.key,12)))) ORDER BY key LIMIT 128 OFFSET ?2",
|
||||
-1, *statement, null) != SQLITE_OK { return -1 }
|
||||
defer { SqliteFinalize(statement) }
|
||||
bind_text(statement, 1, AchievementOwner())
|
||||
@@ -24,8 +24,11 @@ AchievementPhotoBackfill :: (offset: s32) -> s32 {
|
||||
document := AppTextFromCString(SqliteColumnText(statement, 0), 65536)
|
||||
item := MediaParse(document)
|
||||
if item.valid {
|
||||
capture := ReadNumber(document, FieldAt(document, 0, "capture"))
|
||||
day := ifx capture.valid && capture.value == 1 then AchievementParseDay(TextUntilNul(item.day[:])) else 0
|
||||
// Entity records say true; a released version's library said 1.
|
||||
capture_at := FieldAt(document, 0, "capture")
|
||||
capture := ReadNumber(document, capture_at)
|
||||
captured := MatchLiteral(document, capture_at, "true") || (capture.valid && capture.value == 1)
|
||||
day := ifx captured then AchievementParseDay(TextUntilNul(item.day[:])) else 0
|
||||
unused AchievementRecord("photo.original", TextUntilNul(item.hash[:]), day, 1, "", "", false, false, item.trashed)
|
||||
}
|
||||
rows += 1
|
||||
|
||||
+79
-40
@@ -568,40 +568,70 @@ capture dates remain in the shared record. Small, transparent and animated
|
||||
images retain their bytes, as do photos already in the library.
|
||||
|
||||
The library belongs to the account, not to Photos, so its photos stay when
|
||||
Photos is removed. The host keeps it (`src/cells/media_store.zi`): each photo
|
||||
is stored once by the SHA-256 of its bytes under
|
||||
`media/<account>/<sha256>`, with an upright JPEG preview of at most 512
|
||||
pixels (`<sha256>.preview`) made on import by Kryon's `ImagePreview`
|
||||
(`image_preview.zi`: the host decodes, portable Ziran scales by area
|
||||
averages, turns by the Exif orientation and writes a baseline JPEG). The
|
||||
capture day and time come from the file's Exif original date
|
||||
(`media_metadata.zi`), otherwise from the day it was added. Records sync in
|
||||
their own collection, `private.inbe.v1.media`, which released versions skip:
|
||||
Photos is removed. Each photo is a record of the account's entity data
|
||||
(Daochi `docs/entity-data.md`), which every app of the account shares: Diary
|
||||
embeds the same photo, and other apps such as the standalone Photos read and
|
||||
write the same record. Everything there is private. The host keeps it
|
||||
(`src/cells/media_store.zi`, `entity_photos.zi`): each photo is stored once
|
||||
by the SHA-256 of its bytes under `media/<account>/<sha256>`, with an
|
||||
upright JPEG preview of at most 512 pixels (`<sha256>.preview`) made on
|
||||
import by Kryon's `ImagePreview` (`image_preview.zi`: the host decodes,
|
||||
portable Ziran scales by area averages, turns by the Exif orientation and
|
||||
writes a baseline JPEG). The capture day and time come from the file's Exif
|
||||
original date (`media_metadata.zi`), otherwise from the day it was added.
|
||||
The record is `entity.photos.<sha256>` on the device and record `<sha256>`
|
||||
of `private.entity.v1.photos` in the account's signed v6 sync, sealed in
|
||||
Daochi's record profile (`storage/entity_record_crypto.zi`: XChaCha20-Poly1305
|
||||
with the account's photos record key, key ID `entity-v1`, the same bytes as
|
||||
libsodium's):
|
||||
|
||||
```json
|
||||
{"hash","size","type":"image/jpeg","taken_at","width","height",
|
||||
"blobs":[{"address","size"}],"preview":{"hash","size","type","blobs"},
|
||||
"added_at","name","trashed":false,"day","taken","capture":true}
|
||||
```
|
||||
|
||||
`blobs` names the photo's sealed chunks once a node has them all, and the
|
||||
preview names its own. Fields this version does not know are kept when it
|
||||
writes a record back, and an entity record of another kind, or one that does
|
||||
not open, changes nothing and never stops a sync. A record that arrives
|
||||
replaces this device's copy, keeping fields only this device has, unless a
|
||||
change here has not gone out yet; that change then goes out over it.
|
||||
|
||||
Released versions kept the library in `private.inbe.v1.media`, which they
|
||||
read through 2027-10-24, and each photo's bytes as one old sealed copy at
|
||||
`/api/v1/blobs/inbe/` (`diary_records.zi`):
|
||||
|
||||
| Key | Value |
|
||||
|---|---|
|
||||
| `cell.media.<sha256>` | `{"hash","size","type","name","day","taken","added","trashed"[,"blob","key"]}` |
|
||||
| `cell.media.preview.<sha256>` | `{"hash","size","type"[,"blob","key"]}` |
|
||||
| `cell.media.<sha256>` | `{"hash","size","type","name","day","taken","added","trashed"[,"blob","key"][,"photo"]}` |
|
||||
| `cell.media.preview.<sha256>` | `{"hash","size","type"[,"blob","key"][,"photo"]}` |
|
||||
|
||||
Diary photos older versions attached as Diary files belong to the library
|
||||
too (`media_diary_photos.zi`): each Diary file a day's entry still includes,
|
||||
by a `photos` row or a `diary:` embed, joins it once by its hash through the
|
||||
photo button's path (`MediaAddBytes`), named as the entry names it and,
|
||||
without an Exif date, under the entry's day (`taken` is then the day
|
||||
alone). The entry is not rewritten. A Diary file no entry includes stays
|
||||
out, and an existing `cell.media.<sha256>` record, in Trash or not, is left
|
||||
as it is. The library file is a hard link to the Diary file where the
|
||||
platform allows (a copy on the web), and its sealed copy is the Diary
|
||||
photo's, so nothing is kept or uploaded twice. A check is due at start, for
|
||||
another account, after each good sync and when a photo's file arrives; it
|
||||
reads the day entries only when the Diary files outside the library or the
|
||||
entries changed, and adds four photos per frame while the person is idle
|
||||
and no practice shows.
|
||||
Those photos and Diary photos older versions attached as Diary files move to
|
||||
the entity data (`media_diary_photos.zi`). A library photo moves once its
|
||||
bytes are on the device, its old copy downloading for it, and its entity
|
||||
record takes its name, day, Trash and the time it was added. Each Diary file
|
||||
a day's entry still includes, by a `photos` row or a `diary:` embed, moves by
|
||||
its hash through the photo button's path (`MediaAddBytes`), named as the
|
||||
entry names it and, without an Exif date, under the entry's day (`taken` is
|
||||
then the day alone); its library file is a hard link to the Diary file where
|
||||
the platform allows. Entries are not rewritten, and Diary draws a moved photo
|
||||
by its hash. A Diary file no entry includes stays as it is. Once the sync
|
||||
node confirmed a moved photo's record and chunks and the media pass
|
||||
downloaded them back whole (`verified_contents`), its old records name it,
|
||||
`"photo": "<sha256>"`, keeping every other field; then its Diary file
|
||||
leaves the device, its hex chunks from before copies shrink to one byte
|
||||
each, and the media pass deletes its old copies from every node
|
||||
(`old_copies_deleted`). Any failure keeps the old copy for a later pass, and
|
||||
a delegate (Telegram) device moves nothing. A check is due at start, for
|
||||
another account, after each good sync and when a photo's file arrives or
|
||||
comes back whole; it reads the day entries only when what has not moved or
|
||||
the entries changed, and moves four photos per frame while the person is
|
||||
idle and no practice shows.
|
||||
|
||||
The apply branch accepts any `cell.media.*` key with a JSON value, so a later
|
||||
version can add kinds of records; a record this version cannot read changes
|
||||
nothing and never stops a sync. `media` is a reserved app name, so these keys
|
||||
are never taken for an app's records.
|
||||
The legacy apply branch still accepts any `cell.media.*` key with a JSON
|
||||
value, so released versions' records keep syncing; `media` is a reserved app
|
||||
name, so these keys are never taken for an app's records.
|
||||
|
||||
Apps reach the library only through the media calls, which the host grants
|
||||
to Photos alone among the apps the node offers (`NodeAppMediaGranted`); a
|
||||
@@ -618,12 +648,15 @@ pick did, the library's revision and this device's date, and
|
||||
`MediaUpdateHost(hash, field, value)` changes `trashed` or `name`. The hosted
|
||||
asset policy draws `media/` paths of the current account's library only.
|
||||
|
||||
Photo bytes travel as the Diary's sealed copies (`diary_records.zi`): a key
|
||||
made from the account's Diary copy key and the file's hash, ChaCha20-Poly1305
|
||||
with a fixed nonce, `PUT /api/v1/blobs/inbe/<sha256 of the copy>`. The same
|
||||
picture in Diary and in the library is therefore the same copy, uploaded once
|
||||
per node. The media pass (`diary_blobs.zi`) moves Diary photos, library
|
||||
originals and previews after each good sync:
|
||||
Photo bytes travel as the entity data's sealed chunks: chunks of at most
|
||||
8 MiB, each sealed with a key made from the account key, the photo's hash and
|
||||
the chunk's index (DaochiClient's `entity.zi`), ChaCha20-Poly1305 with a zero
|
||||
nonce, `PUT /api/v1/blobs/entity/<sha256 of the chunk>`, signed with Inbe's
|
||||
own app ID and device key. The same picture is therefore the same chunks for
|
||||
every app of the account, uploaded once per node. The media pass
|
||||
(`diary_blobs.zi`) moves photos, previews, the old copies photos still need
|
||||
in order to move, and deletes of moved photos' old copies after each good
|
||||
sync:
|
||||
|
||||
- Copies go to every node in the account's node list whose photo upload is
|
||||
on (Profile › Data), not only the sync node. `diary_blobs(node, blob)`
|
||||
@@ -632,7 +665,9 @@ originals and previews after each good sync:
|
||||
only that node full; a node that fails only loses its turn.
|
||||
- Downloads ask the sync node first, then the other nodes in list order; a
|
||||
404 moves on to the next node. Previews download everywhere, originals only
|
||||
where they are wanted (`media_wanted`, the last 32 photos opened here).
|
||||
where they are wanted (`media_wanted`, the last 32 photos opened here) or
|
||||
when a photo has no preview. Deletes go first, so a node has room for what
|
||||
moves; a node that answers 405 keeps its old copies for a later pass.
|
||||
- Blob requests never use the sync's session. Each node has its own media
|
||||
session, saved on this device under `SyncNodeCursorKey(address,
|
||||
"media_auth_*")`, opened with a login and a device registration on that
|
||||
@@ -650,10 +685,14 @@ publication the node's importer writes `history-v2.json`, the app's newest
|
||||
three releases, which the node offers for going back to an earlier version;
|
||||
`--write-history` rewrites every app's history. `make
|
||||
media-store-test media-metadata-test photos-app-test` check the library, the
|
||||
Exif reader and the app through the real host; `make sync-server-test`
|
||||
(`DAOCHI_BIN=...`) adds a photo on one device and opens it on another through
|
||||
two real Daochi nodes, and `make photos-ui-test` adds a camera photo through
|
||||
the desktop picker on a private Xvfb display.
|
||||
Exif reader and the app through the real host; `make entity-photos-test`
|
||||
upgrades a 2.1.43 profile (`tests/fixtures/photos-2.1.43.sql`) against nodes
|
||||
answered from memory, with interrupted passes, a full node, an unreachable
|
||||
node, a node that cannot delete and a damaged chunk; `make sync-server-test`
|
||||
(`DAOCHI_BIN=...`, Daochi 17bfd12 or later) adds a photo on one device and
|
||||
opens it on another through two real Daochi nodes and moves an old copy
|
||||
there; and `make photos-ui-test` adds a camera photo through the desktop
|
||||
picker on a private Xvfb display.
|
||||
|
||||
## Account app choices
|
||||
|
||||
|
||||
+6
-1
@@ -37,7 +37,7 @@ app-locations-test: $(ZIRAN_BIN)
|
||||
node-app-snapshot-test: $(ZIRAN_BIN) $(ZIRAN_BUILD_DIR)/libziran.a $(SQLITE_SRC) $(LIBOQS_A)
|
||||
python3 tests/node_app_snapshot_test.py --ziran '$(abspath $(ZIRAN_BIN))' \
|
||||
--runtime '$(abspath $(ZIRAN_BUILD_DIR)/libziran.a)'
|
||||
.PHONY: photos-app-test media-store-test media-metadata-test
|
||||
.PHONY: photos-app-test media-store-test media-metadata-test entity-photos-test
|
||||
# Photos and the account's media library it shows.
|
||||
media-metadata-test: $(ZI2C_BIN)
|
||||
sh tests/media_metadata_test.sh $(ZIRAN_BUILD_DIR)/bin
|
||||
@@ -45,6 +45,11 @@ media-metadata-test: $(ZI2C_BIN)
|
||||
media-store-test: $(ZI2C_BIN) $(SQLITE_SRC) $(LIBOQS_A)
|
||||
sh tests/media_store_zi_test.sh $(ZIRAN_BIN) $(LIBOQS_A)
|
||||
|
||||
# A 2.1.43 profile's Diary and library photos move to the account's entity
|
||||
# data, and old copies go only once the node has the new ones whole.
|
||||
entity-photos-test: $(ZI2C_BIN) $(SQLITE_SRC) $(LIBOQS_A)
|
||||
sh tests/entity_photos_zi_test.sh $(ZIRAN_BIN) $(LIBOQS_A)
|
||||
|
||||
photos-app-test: $(ZIRAN_BIN) $(SQLITE_SRC) $(LIBOQS_A)
|
||||
sh tests/photos_app_test.sh $(ZIRAN_BIN) $(LIBOQS_A)
|
||||
|
||||
|
||||
+1
-1
@@ -128,7 +128,7 @@ test: android-smoke-script-test
|
||||
test: sync-recovery-test
|
||||
test: sync-connection-test
|
||||
test: sync-record-fields-test
|
||||
test: media-metadata-test media-store-test photos-app-test
|
||||
test: media-metadata-test media-store-test entity-photos-test photos-app-test
|
||||
test: node-app-records-test node-app-snapshot-test
|
||||
test: app-click-block-zi-test
|
||||
test: phone-check-gate-test
|
||||
|
||||
@@ -580,6 +580,7 @@ app_social_apply_result :: (app: *InnerBreeze, requests_json: string,
|
||||
CancelStoredBlob(*g_diary_blob)
|
||||
}
|
||||
DiaryBlobAbandon(*g_diary_request)
|
||||
DiaryBlobPassEnd(*g_diary_pass)
|
||||
if g_diary_output != null {
|
||||
SyncWorkerFree(cast(*void)g_diary_output)
|
||||
g_diary_output = null
|
||||
|
||||
+691
-323
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,7 @@ DiaryBlobsSendNative :: (url: string) {
|
||||
return
|
||||
}
|
||||
request: DiaryBlobRequest
|
||||
defer { DiaryBlobPassEnd(*pass) }
|
||||
while DiaryBlobNext(*pass, *request) {
|
||||
capacity: s64 = 4096
|
||||
if request.answer_bytes > capacity {
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
// a photo of the account's media library by its place there,
|
||||
// photos/YYYY/MM/DD/<sha256>.<type>, or to a Diary file an older version
|
||||
// attached, diary:<file>. Diary draws each through an asset path the hosted
|
||||
// asset policy allows: the library's preview, or the Diary file itself.
|
||||
// asset policy allows: the library's preview, or the Diary file itself
|
||||
// while the photo has not moved to the library (media_diary_photos.zi).
|
||||
// A moved photo's Diary file may be gone; its entry still names its hash.
|
||||
#import "vec"
|
||||
#import "text"
|
||||
#import "byte_text_linux"
|
||||
@@ -11,6 +13,7 @@
|
||||
#import, file "diary_store.zi";
|
||||
#import, file "media_store.zi";
|
||||
#import, file "package_files.zi";
|
||||
#import, file "../storage/cell_records.zi";
|
||||
#import, file "../storage/sync_apply.zi";
|
||||
#import, file "../app/text_buffers.zi";
|
||||
|
||||
@@ -48,10 +51,14 @@ DiaryPhotoFile :: (name: string) -> *DiaryPhotoFormat {
|
||||
slot.* = DiaryPhotoFormat.{}
|
||||
unused AppCopyText(name, slot.name[:])
|
||||
unused AppCopyText(format, slot.format[:])
|
||||
media := DiaryMediaRead(name)
|
||||
if format.count > 0 && media.valid && MediaRead(TextFromBytes(media.hash[:64])).valid {
|
||||
slot.library = media.hash
|
||||
key := DiaryRecordKey(name)
|
||||
entry := CellRecordRead(key)
|
||||
hash := DiaryEntryHash(entry)
|
||||
if hash.count == 64 && DiaryRecordMedia(name) && MediaRead(hash).valid {
|
||||
unused AppCopyText(hash, slot.library[:])
|
||||
}
|
||||
PackageFree(key)
|
||||
PackageFree(entry)
|
||||
slot.generation = diary_blob_generation
|
||||
slot.media_changes = storage_media_changes
|
||||
return slot
|
||||
@@ -69,15 +76,15 @@ DiaryPhotoAsset :: (destination: string) -> string {
|
||||
return ""
|
||||
}
|
||||
file := DiaryPhotoFile(name)
|
||||
format := TextUntilNul(file.format[:])
|
||||
if format.count == 0 {
|
||||
return ""
|
||||
}
|
||||
library := TextUntilNul(file.library[:])
|
||||
if library.count == 64 && AppCopyText(MediaAsset(library, false), diary_photo_asset[:]) &&
|
||||
diary_photo_asset[0] != cast(u8)0 {
|
||||
return TextUntilNul(diary_photo_asset[:])
|
||||
}
|
||||
format := TextUntilNul(file.format[:])
|
||||
if format.count == 0 {
|
||||
return ""
|
||||
}
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "diary/photos/%.%", name, format)
|
||||
path := BuilderFinish(out)
|
||||
|
||||
+31
-52
@@ -3,12 +3,15 @@
|
||||
// A day document (YYYY-MM-DD.json) syncs its bytes as hex chunks beside the
|
||||
// entry, which becomes readable only when all chunks and its hash validate.
|
||||
//
|
||||
// A photo or video stays a file on the device. Its entry syncs
|
||||
// {"hash","size"}; once its sealed copy is on a node it also names that copy,
|
||||
// "blob" (the copy's SHA-256, its address on the node) and "key". The copy is
|
||||
// the file sealed with a key made for that file alone, so it takes the
|
||||
// file's size plus 16 bytes. Entries with "count" are photos from before,
|
||||
// still kept as chunks until their copy is uploaded (diary_blobs.zi).
|
||||
// A photo or video an older version attached stays a file on the device.
|
||||
// Its entry syncs {"hash","size"}; once a released version put its sealed
|
||||
// old copy on a node it also names that copy, "blob" (the copy's SHA-256,
|
||||
// its address on the node) and "key". The copy is the file sealed with a key
|
||||
// made for that file alone, so it takes the file's size plus 16 bytes.
|
||||
// Entries with "count" are photos from before copies, kept as hex chunks.
|
||||
// Such photos move to the account's entity data (media_diary_photos.zi);
|
||||
// then the entry also names it, "photo" (its SHA-256), and keeps its other
|
||||
// fields for released versions.
|
||||
#import "json_scan"
|
||||
#import "byte_text_linux"
|
||||
#import "vec"
|
||||
@@ -24,10 +27,12 @@
|
||||
|
||||
DIARY_CHUNK_BYTES :: 1024
|
||||
DIARY_FILE_LIMIT :: 16777216
|
||||
// Sealing adds a 16-byte tag; the nonce is fixed (see DiaryBlobSeal).
|
||||
// Released versions sealed each photo as one old copy with a key made for
|
||||
// that file alone, from the account key with the context
|
||||
// "inbe-diary-blob-key-v1", a zero nonce and this associated data; sealing
|
||||
// adds a 16-byte tag. Photos move from there to the account's entity data
|
||||
// (media_diary_photos.zi), and old copies are only opened.
|
||||
DIARY_BLOB_TAG :: 16
|
||||
// The account's Diary copy key comes from the account key with this context.
|
||||
DIARY_BLOB_CONTEXT :: "inbe-diary-blob-key-v1"
|
||||
DIARY_BLOB_AAD :: "inbe.diary.blob.v1"
|
||||
|
||||
diary_records_c :: #system_library "c";
|
||||
@@ -147,6 +152,9 @@ DiaryMedia :: struct {
|
||||
// Both empty until the sealed copy is on a node.
|
||||
blob: [65]u8
|
||||
key: [65]u8
|
||||
// The photo moved to the account's entity data, and the entry names its
|
||||
// record, "photo" (media_diary_photos.zi).
|
||||
pointed: bool
|
||||
}
|
||||
|
||||
DiaryHex64 :: (text: string) -> bool {
|
||||
@@ -173,6 +181,9 @@ DiaryMediaParse :: (entry: string) -> DiaryMedia {
|
||||
return DiaryMedia.{}
|
||||
}
|
||||
result.size = cast(s64)size.value
|
||||
photo: [65]u8
|
||||
result.pointed = ReadStringText(entry, FieldAt(entry, 0, "photo"), photo[:]) == 64 &&
|
||||
TextFromBytes(photo[:64]) == TextFromBytes(result.hash[:64])
|
||||
if FieldAt(entry, 0, "blob") >= 0 {
|
||||
if ReadStringText(entry, FieldAt(entry, 0, "blob"), result.blob[:]) != 64 ||
|
||||
ReadStringText(entry, FieldAt(entry, 0, "key"), result.key[:]) != 64 ||
|
||||
@@ -184,6 +195,17 @@ DiaryMediaParse :: (entry: string) -> DiaryMedia {
|
||||
return result
|
||||
}
|
||||
|
||||
// The hash an entry names, with or without chunks, or empty. The answer
|
||||
// is a view of the entry.
|
||||
DiaryEntryHash :: (entry: string) -> string {
|
||||
at := FieldAt(entry, 0, "hash")
|
||||
span := ReadString(entry, at)
|
||||
if at < 0 || !span.valid || span.end - span.start != 64 || !DiaryHex64(entry[span.start:span.end]) {
|
||||
return ""
|
||||
}
|
||||
return entry[span.start:span.end]
|
||||
}
|
||||
|
||||
DiaryMediaRead :: (name: string) -> DiaryMedia {
|
||||
key := DiaryRecordKey(name)
|
||||
entry := CellRecordRead(key)
|
||||
@@ -206,18 +228,6 @@ DiaryMediaMatches :: (media: DiaryMedia, data: string) -> bool {
|
||||
return TextFromCString(*actual[0]) == TextFromBytes(media.hash[:64])
|
||||
}
|
||||
|
||||
// The key that seals one file comes from the account's Diary key and the
|
||||
// file's hash, so every device of the account makes the same copy.
|
||||
DiaryBlobKey :: (hash: string, output: *u8) -> bool {
|
||||
master: [32]u8
|
||||
if storage_private_record_key_for_context(DIARY_BLOB_CONTEXT, *master[0]) == 0 {
|
||||
return false
|
||||
}
|
||||
ok := HmacSha256Text(*master[0], 32, hash, output) != 0
|
||||
SecureWipe(*master[0], 32)
|
||||
return ok
|
||||
}
|
||||
|
||||
DiaryBlobAad :: (output: []u8) {
|
||||
text := DIARY_BLOB_AAD
|
||||
for index: cast(s64)0..text.count - 1 {
|
||||
@@ -225,29 +235,6 @@ DiaryBlobAad :: (output: []u8) {
|
||||
}
|
||||
}
|
||||
|
||||
// The file sealed for a node, or "" when it cannot be sealed. Its key seals
|
||||
// only this file, so the fixed zero nonce is never used twice with a key.
|
||||
DiaryBlobSeal :: (data: string, key: *u8) -> string {
|
||||
if data.count <= 0 || data.count > DIARY_FILE_LIMIT {
|
||||
return ""
|
||||
}
|
||||
count := data.count + DIARY_BLOB_TAG
|
||||
output := cast(*u8)DiaryAllocate(cast(usize)count)
|
||||
if output == null {
|
||||
return ""
|
||||
}
|
||||
nonce: [12]u8
|
||||
aad: [32]u8
|
||||
DiaryBlobAad(aad[:])
|
||||
descriptor := cast(*TextDescriptor)(*data)
|
||||
if ChaCha20Poly1305Seal(key, *nonce[0], descriptor.data, data.count, *aad[0],
|
||||
cast(s64)DIARY_BLOB_AAD.count, output, count) == 0 {
|
||||
DiaryRelease(cast(*void)output)
|
||||
return ""
|
||||
}
|
||||
return TextFromBytes(BytesFromPointer(output, cast(u64)count))
|
||||
}
|
||||
|
||||
// The file inside a sealed copy, or "" when the copy is not the one its
|
||||
// entry names.
|
||||
DiaryBlobOpen :: (media: DiaryMedia, sealed: []u8) -> string {
|
||||
@@ -281,11 +268,3 @@ DiaryBlobOpen :: (media: DiaryMedia, sealed: []u8) -> string {
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// The entry once the sealed copy is on a node.
|
||||
DiaryMediaUploadedEntry :: (media: DiaryMedia, blob: string, key: string) -> string {
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "{\"hash\":\"%\",\"size\":%,\"blob\":\"%\",\"key\":\"%\"}",
|
||||
TextFromBytes(media.hash[:64]), media.size, blob, key)
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
// The account's photos as entity records (Daochi docs/entity-data.md,
|
||||
// storage/entity_records.zi), shared by every app of the account:
|
||||
//
|
||||
// entity.photos.<sha256> {"hash","size","type","taken_at","width","height",
|
||||
// "blobs":[{"address","size"}],
|
||||
// "preview":{"hash","size","type","blobs"},
|
||||
// "added_at","name","trashed","day","taken","capture"}
|
||||
//
|
||||
// "type" is the MIME type, "size" the plain size of the whole content, and
|
||||
// each "blobs" entry one sealed chunk of at most 8 MiB plain bytes, in order,
|
||||
// with its sealed size. A record names its chunks once they are on a node
|
||||
// (diary_blobs.zi), and the preview names its own. "day" is the capture day
|
||||
// on the camera's clock and "taken" the capture time as the camera wrote it;
|
||||
// fields this version does not know are kept when it writes a record back.
|
||||
#import "byte_text_linux"
|
||||
#import "vec"
|
||||
#import "text"
|
||||
#import "json_scan"
|
||||
#import "text_buffer"
|
||||
#import "daochi_client/entity"
|
||||
#import, file "package_files.zi";
|
||||
#import, file "../storage/entity_records.zi";
|
||||
#import, file "../storage/media_records.zi";
|
||||
#import, file "../storage/storage_core.zi";
|
||||
#import, file "../storage/sqlite.zi";
|
||||
#import, file "../storage/db.zi";
|
||||
#import, file "../storage/state.zi";
|
||||
#import, file "../app/text_buffers.zi";
|
||||
|
||||
// Content of at most the Diary's 16 MiB file limit has two chunks; records
|
||||
// of larger content from other apps list more and stay on the node.
|
||||
ENTITY_PHOTO_CHUNKS :: 8
|
||||
ENTITY_PHOTO_LOCAL_CHUNKS :: 2
|
||||
|
||||
EntityChunk :: struct {
|
||||
address: [65]u8
|
||||
size: s64
|
||||
}
|
||||
|
||||
// One content of a photo record: the photo itself or its preview.
|
||||
EntityContent :: struct {
|
||||
valid: bool
|
||||
hash: [65]u8
|
||||
size: s64
|
||||
// png, jpg, gif or webp; empty for a type this version does not show.
|
||||
format: [8]u8
|
||||
// The chunks on a node, in order; none until they are there.
|
||||
chunks: [ENTITY_PHOTO_CHUNKS]EntityChunk
|
||||
chunk_count: s32
|
||||
}
|
||||
|
||||
EntityPhotoKey :: (hash: string) -> string {
|
||||
return PackageText(ENTITY_PHOTO_PREFIX, hash)
|
||||
}
|
||||
|
||||
// The chunks content of `size` plain bytes is cut into.
|
||||
EntityChunkCount :: (size: s64) -> s32 {
|
||||
return cast(s32)((size + ENTITY_CHUNK_BYTES - 1) / ENTITY_CHUNK_BYTES)
|
||||
}
|
||||
|
||||
// The plain bytes of chunk `index` within content of `size` bytes.
|
||||
EntityChunkPlain :: (size: s64, index: s32) -> s64 {
|
||||
start := cast(s64)index * ENTITY_CHUNK_BYTES
|
||||
rest := size - start
|
||||
if rest > ENTITY_CHUNK_BYTES {
|
||||
return ENTITY_CHUNK_BYTES
|
||||
}
|
||||
return rest
|
||||
}
|
||||
|
||||
EntityFormatOfType :: (type_name: string) -> string {
|
||||
if type_name == "image/png" {
|
||||
return "png"
|
||||
}
|
||||
if type_name == "image/jpeg" {
|
||||
return "jpg"
|
||||
}
|
||||
if type_name == "image/gif" {
|
||||
return "gif"
|
||||
}
|
||||
if type_name == "image/webp" {
|
||||
return "webp"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
EntityTypeOfFormat :: (format: string) -> string {
|
||||
if format == "jpg" {
|
||||
return "image/jpeg"
|
||||
}
|
||||
if format == "gif" {
|
||||
return "image/gif"
|
||||
}
|
||||
if format == "webp" {
|
||||
return "image/webp"
|
||||
}
|
||||
return "image/png"
|
||||
}
|
||||
|
||||
// The content described by the object at `at`: the record itself (0) or
|
||||
// its "preview". Chunks that do not match the content's size are not its
|
||||
// chunks, and leave it without any.
|
||||
EntityContentAt :: (record: string, at: s32) -> EntityContent {
|
||||
content: EntityContent
|
||||
if at < 0 || at >= cast(s32)record.count || record[at] != cast(u8)123 {
|
||||
return content
|
||||
}
|
||||
size := ReadNumber(record, FieldAt(record, at, "size"))
|
||||
type_name: [64]u8
|
||||
if ReadStringText(record, FieldAt(record, at, "hash"), content.hash[:]) != 64 ||
|
||||
!MediaHashValid(TextFromBytes(content.hash[:64])) || !size.valid || size.value < 1.0 ||
|
||||
size.value > cast(float64)ENTITY_CHUNK_BYTES * cast(float64)ENTITY_PHOTO_CHUNKS {
|
||||
return EntityContent.{}
|
||||
}
|
||||
content.size = cast(s64)size.value
|
||||
if cast(float64)content.size != size.value {
|
||||
return EntityContent.{}
|
||||
}
|
||||
type_count := ReadStringText(record, FieldAt(record, at, "type"), type_name[:])
|
||||
if type_count > 0 && type_count < 64 {
|
||||
unused AppCopyText(EntityFormatOfType(TextFromBytes(type_name[:type_count])), content.format[:])
|
||||
}
|
||||
content.valid = true
|
||||
blobs := FieldAt(record, at, "blobs")
|
||||
count := ArrayCount(record, blobs)
|
||||
if count != EntityChunkCount(content.size) {
|
||||
return content
|
||||
}
|
||||
for index: cast(s32)0..count - 1 {
|
||||
chunk := ElementAt(record, blobs, index)
|
||||
sealed := ReadNumber(record, FieldAt(record, chunk, "size"))
|
||||
entry := *content.chunks[index]
|
||||
if ReadStringText(record, FieldAt(record, chunk, "address"), entry.address[:]) != 64 ||
|
||||
!MediaHashValid(TextFromBytes(entry.address[:64])) || !sealed.valid ||
|
||||
sealed.value != cast(float64)(EntityChunkPlain(content.size, index) + 16) {
|
||||
content.chunk_count = 0
|
||||
return content
|
||||
}
|
||||
entry.size = cast(s64)sealed.value
|
||||
}
|
||||
content.chunk_count = count
|
||||
return content
|
||||
}
|
||||
|
||||
EntityPhotoContent :: (record: string) -> EntityContent {
|
||||
return EntityContentAt(record, 0)
|
||||
}
|
||||
|
||||
EntityPreviewContent :: (record: string) -> EntityContent {
|
||||
return EntityContentAt(record, FieldAt(record, 0, "preview"))
|
||||
}
|
||||
|
||||
// Whether the bytes are exactly this content.
|
||||
EntityContentMatches :: (content: EntityContent, data: string) -> bool {
|
||||
if !content.valid || data.count != content.size {
|
||||
return false
|
||||
}
|
||||
descriptor := cast(*TextDescriptor)(*data)
|
||||
actual: [65]u8
|
||||
storage_sha256_hex(descriptor.data, data.count, *actual[0])
|
||||
return TextFromCString(*actual[0]) == TextFromBytes(content.hash[:64])
|
||||
}
|
||||
|
||||
// The "blobs" list naming these chunks.
|
||||
EntityBlobsJson :: (chunks: []EntityChunk) -> string {
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "[")
|
||||
for index: cast(s64)0..chunks.count - 1 {
|
||||
if index > 0 {
|
||||
BuilderPrint(*out, ",")
|
||||
}
|
||||
BuilderPrint(*out, "{\"address\":\"%\",\"size\":%}", TextUntilNul(chunks[index].address[:]),
|
||||
chunks[index].size)
|
||||
}
|
||||
BuilderPrint(*out, "]")
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
// Whether the node has every chunk of this content, as this device knows
|
||||
// from what it put there or fetched from there (diary_blobs).
|
||||
EntityContentOnNode :: (content: EntityContent, node: string) -> bool {
|
||||
if !content.valid || content.chunk_count == 0 || storage_db_handle() == null {
|
||||
return false
|
||||
}
|
||||
for index: cast(s32)0..content.chunk_count - 1 {
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(),
|
||||
"SELECT 1 FROM diary_blobs WHERE node=?1 AND blob=?2", -1, *statement, null) != SQLITE_OK {
|
||||
return false
|
||||
}
|
||||
unused bind_text(statement, 1, node)
|
||||
unused bind_text(statement, 2, TextUntilNul(content.chunks[index].address[:]))
|
||||
found := SqliteStep(statement) == SQLITE_ROW
|
||||
SqliteFinalize(statement)
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Whether this device downloaded the content back from the node and found
|
||||
// it whole (diary_blobs.zi).
|
||||
EntityContentVerified :: (content: EntityContent, node: string) -> bool {
|
||||
if !content.valid || storage_db_handle() == null {
|
||||
return false
|
||||
}
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(),
|
||||
"SELECT 1 FROM verified_contents WHERE node=?1 AND hash=?2", -1, *statement, null) != SQLITE_OK {
|
||||
return false
|
||||
}
|
||||
defer { SqliteFinalize(statement) }
|
||||
unused bind_text(statement, 1, node)
|
||||
unused bind_text(statement, 2, TextUntilNul(content.hash[:]))
|
||||
return SqliteStep(statement) == SQLITE_ROW
|
||||
}
|
||||
|
||||
// Whether every content of the photo, itself and its preview, came back
|
||||
// whole from the node.
|
||||
EntityPhotoVerified :: (record: string, node: string) -> bool {
|
||||
photo := EntityPhotoContent(record)
|
||||
if !EntityContentVerified(photo, node) {
|
||||
return false
|
||||
}
|
||||
return FieldAt(record, 0, "preview") < 0 || EntityContentVerified(EntityPreviewContent(record), node)
|
||||
}
|
||||
|
||||
EntityPhotoConfirmedSQL :: #string SQL_END
|
||||
SELECT 1 FROM settings s JOIN sync_record_copies c
|
||||
ON c.collection=?3 AND c.id=?4 AND json_valid(c.json)
|
||||
WHERE s.user_id=?1 AND s.key=?2 AND json_valid(s.value)
|
||||
AND json_extract(c.json,'$.blobs')=json_extract(s.value,'$.blobs')
|
||||
AND COALESCE(json_extract(c.json,'$.preview.blobs'),'')=COALESCE(json_extract(s.value,'$.preview.blobs'),'')
|
||||
AND NOT EXISTS (SELECT 1 FROM sync_outbox WHERE entity_type='entity_record' AND entity_id=?2)
|
||||
SQL_END;
|
||||
|
||||
// Whether the sync node has the photo's record as this device has it,
|
||||
// naming its chunks and its preview's: an upload of it was answered, or it
|
||||
// arrived from there, and no change of it waits to go out.
|
||||
EntityPhotoAcknowledged :: (hash: string, record: string) -> bool {
|
||||
photo := EntityPhotoContent(record)
|
||||
if !photo.valid || TextFromBytes(photo.hash[:64]) != hash || photo.chunk_count == 0 {
|
||||
return false
|
||||
}
|
||||
key := EntityPhotoKey(hash)
|
||||
defer { PackageFree(key) }
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(), EntityPhotoConfirmedSQL, -1, *statement, null) != SQLITE_OK {
|
||||
return false
|
||||
}
|
||||
defer { SqliteFinalize(statement) }
|
||||
unused bind_text(statement, 1, AppTextFromCString(storage_user_id_buffer(), 64))
|
||||
unused bind_text(statement, 2, key)
|
||||
unused bind_text(statement, 3, EntityPhotosCollection)
|
||||
unused bind_text(statement, 4, hash)
|
||||
return SqliteStep(statement) == SQLITE_ROW
|
||||
}
|
||||
|
||||
// Whether the sync node confirmed this photo: it has the record as this
|
||||
// device has it and every chunk the record names, of the photo and its
|
||||
// preview. Only then may an old copy of the photo go.
|
||||
EntityPhotoConfirmed :: (hash: string, record: string, node: string) -> bool {
|
||||
if !EntityPhotoAcknowledged(hash, record) || !EntityContentOnNode(EntityPhotoContent(record), node) {
|
||||
return false
|
||||
}
|
||||
return FieldAt(record, 0, "preview") < 0 || EntityContentOnNode(EntityPreviewContent(record), node)
|
||||
}
|
||||
+362
-36
@@ -1,21 +1,35 @@
|
||||
// Diary photos in the account's media library. A photo an older version
|
||||
// attached to a Diary entry is a Diary file (diary_records.zi), which Photos
|
||||
// does not list. Each Diary file that a day's entry still includes, by a row
|
||||
// of its "photos" list or a diary: embed in its text, joins the library once
|
||||
// by its hash, as a photo the photo button adds does (MediaAddBytes): named
|
||||
// as the entry names it and, without a camera date, under the entry's day.
|
||||
// The entry keeps its diary: embed and is never rewritten.
|
||||
// Photos move to the account's entity data (entity_photos.zi), so each is
|
||||
// kept once for the account, whichever app shows it:
|
||||
//
|
||||
// A Diary file no entry names stays out, and a photo the library already
|
||||
// has, in Trash or not, is left as it is. Its library file is a link to the
|
||||
// Diary file where the platform allows, and its copy on a node is the Diary
|
||||
// photo's own copy (the same key and address), so nothing is kept or
|
||||
// uploaded twice.
|
||||
// - A photo a released version's library keeps, cell.media.<sha256>,
|
||||
// without an entity record moves once its bytes are on this device (its
|
||||
// old copy downloads for it, diary_blobs.zi): its entity record takes
|
||||
// that record's name, day, Trash and the time it was added
|
||||
// (MediaAddBytes).
|
||||
// - A photo an older version attached to a Diary entry is a Diary file
|
||||
// (diary_records.zi). Each Diary file that a day's entry still includes,
|
||||
// by a row of its "photos" list or a diary: embed in its text, moves the
|
||||
// same way, named as the entry names it and, without a camera date,
|
||||
// under the entry's day. Its library file is a link to the Diary file
|
||||
// where the platform allows. The entry keeps its diary: embed and is
|
||||
// never rewritten; Diary draws the photo by its hash (diary_photos.zi).
|
||||
// - Once the sync node confirmed the photo's entity record and chunks and
|
||||
// this device downloaded them back whole (diary_blobs.zi), the photo's
|
||||
// old records name it, {"photo": "<sha256>"}, keeping every field for
|
||||
// released versions, which read them through 2027-10-24. Then its Diary
|
||||
// file leaves this device, its hex chunks from before copies shrink to
|
||||
// one byte each, and the media pass deletes its old copies from the
|
||||
// account's nodes.
|
||||
//
|
||||
// A Diary file no entry includes stays as it is, and so does every old copy
|
||||
// whose photo is not confirmed yet. A delegate (Telegram) device moves
|
||||
// nothing.
|
||||
//
|
||||
// A check is due at start, for another account, after each good sync and
|
||||
// whenever a photo's file arrives. It reads the day entries only when the
|
||||
// Diary files outside the library or the entries changed since the last
|
||||
// check, and adds a few photos at a time.
|
||||
// whenever a photo's file arrives or comes back whole. It reads the day
|
||||
// entries only when the photos that have not moved, or the entries,
|
||||
// changed since the last check, and moves a few photos at a time.
|
||||
#import "file_linux"
|
||||
#import "vec"
|
||||
#import "text"
|
||||
#import "byte_text_linux"
|
||||
@@ -23,18 +37,25 @@
|
||||
#import "json_scan"
|
||||
#import, file "diary_records.zi";
|
||||
#import, file "diary_store.zi";
|
||||
#import, file "entity_photos.zi";
|
||||
#import, file "media_store.zi";
|
||||
#import, file "package_files.zi";
|
||||
#import, file "../storage/cell_records.zi";
|
||||
#import, file "../storage/entity_records.zi";
|
||||
#import, file "../storage/media_records.zi";
|
||||
#import, file "../storage/storage_core.zi";
|
||||
#import, file "../storage/storage_settings.zi";
|
||||
#import, file "../storage/sqlite.zi";
|
||||
#import, file "../storage/db.zi";
|
||||
#import, file "../storage/state.zi";
|
||||
#import, file "../storage/sync_nodes.zi";
|
||||
#import, file "../storage/temporary_data.zi";
|
||||
#import, file "../storage/paths.zi";
|
||||
#import, file "../app/text_buffers.zi";
|
||||
DiaryMarkdown :: #import, file "../../apps/diary/diary_markdown.zi";
|
||||
|
||||
MEDIA_DIARY_PHOTOS_MAX :: 1024
|
||||
// Photos one step adds; each one makes a preview.
|
||||
// Photos one step moves; each one makes a preview.
|
||||
MEDIA_DIARY_PHOTOS_PER_STEP :: 4
|
||||
|
||||
MediaDiaryPhoto :: struct {
|
||||
@@ -48,9 +69,13 @@ MediaDiaryPhoto :: struct {
|
||||
name: [MEDIA_NAME_MAX + 1]u8
|
||||
}
|
||||
|
||||
// Diary files the library does not have, from the last look.
|
||||
// Diary files that have not moved, from the last look.
|
||||
media_diary_photos: [MEDIA_DIARY_PHOTOS_MAX]MediaDiaryPhoto;
|
||||
media_diary_photo_count: s32;
|
||||
// Library photos of a released version that have not moved and whose
|
||||
// bytes are here.
|
||||
media_library_photos: [MEDIA_DIARY_PHOTOS_MAX][65]u8;
|
||||
media_library_photo_count: s32;
|
||||
media_diary_due: bool = true;
|
||||
media_diary_owner: [72]u8;
|
||||
media_diary_generation: s64 = -1;
|
||||
@@ -58,30 +83,60 @@ media_diary_generation: s64 = -1;
|
||||
// again.
|
||||
media_diary_seen: u64;
|
||||
media_diary_seen_valid: bool;
|
||||
// A check is adding its photos, from media_diary_next on.
|
||||
// A check is moving its photos, from media_diary_next and
|
||||
// media_library_next on.
|
||||
media_diary_adding: bool;
|
||||
media_diary_next: s32;
|
||||
media_library_next: s32;
|
||||
|
||||
MediaDiaryPhotosSQL :: #string SQL_END
|
||||
SELECT substr(d.key,17),d.value FROM settings d
|
||||
WHERE d.user_id=?1 AND d.key GLOB 'cell.diary.file.*' AND d.key NOT GLOB '*.json'
|
||||
AND json_valid(d.value)
|
||||
AND NOT EXISTS (SELECT 1 FROM settings m WHERE m.user_id=?1
|
||||
AND m.key='cell.media.'||json_extract(d.value,'$.hash'))
|
||||
AND json_valid(d.value) AND json_type(d.value,'$.photo') IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM settings e WHERE e.user_id=?1
|
||||
AND e.key='entity.photos.'||json_extract(d.value,'$.hash'))
|
||||
ORDER BY d.key
|
||||
SQL_END;
|
||||
|
||||
MediaLibraryPhotosSQL :: #string SQL_END
|
||||
SELECT substr(l.key,12),json_extract(l.value,'$.size') FROM settings l
|
||||
WHERE l.user_id=?1 AND l.key GLOB 'cell.media.*' AND length(l.key)=75
|
||||
AND substr(l.key,12) NOT GLOB '*[^0-9a-f]*' AND json_valid(l.value)
|
||||
AND json_type(l.value,'$.photo') IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM settings e WHERE e.user_id=?1 AND e.key='entity.photos.'||substr(l.key,12))
|
||||
ORDER BY l.key
|
||||
SQL_END;
|
||||
|
||||
MediaDiaryEntriesSQL :: #string SQL_END
|
||||
SELECT key,value FROM settings
|
||||
WHERE user_id=?1 AND key GLOB 'cell.diary.file.????-??-??.json'
|
||||
ORDER BY key
|
||||
SQL_END;
|
||||
|
||||
// The old records of moved photos that do not name their entity record
|
||||
// yet: each with the photo's hash.
|
||||
MediaOldRecordsSQL :: #string SQL_END
|
||||
SELECT o.key,o.value,
|
||||
CASE WHEN o.key GLOB 'cell.diary.file.*' THEN json_extract(o.value,'$.hash') ELSE substr(o.key,length(o.key)-63) END
|
||||
FROM settings o
|
||||
WHERE o.user_id=?1 AND json_valid(o.value) AND json_type(o.value,'$.photo') IS NULL
|
||||
AND ((o.key GLOB 'cell.diary.file.*' AND o.key NOT GLOB '*.json')
|
||||
OR (o.key GLOB 'cell.media.*' AND (length(o.key)=75 OR length(o.key)=83)))
|
||||
AND EXISTS (SELECT 1 FROM settings e WHERE e.user_id=?1 AND e.key='entity.photos.'||
|
||||
CASE WHEN o.key GLOB 'cell.diary.file.*' THEN json_extract(o.value,'$.hash') ELSE substr(o.key,length(o.key)-63) END)
|
||||
ORDER BY o.key
|
||||
SQL_END;
|
||||
|
||||
// Asks for a check, such as after a sync brought entries.
|
||||
MediaDiaryPhotosDue :: () {
|
||||
media_diary_due = true
|
||||
}
|
||||
|
||||
// Whether this device may move photos: not a delegate's.
|
||||
MediaMovesAllowed :: () -> bool {
|
||||
return storage_delegate_mode == null || storage_delegate_mode() != 2
|
||||
}
|
||||
|
||||
// An FNV-1a style checksum step, with a separator after the text.
|
||||
MediaDiaryMix :: (checksum: u64, text: string) -> u64 {
|
||||
value := checksum
|
||||
@@ -124,11 +179,12 @@ MediaDiaryPhotoRead :: (file: string, entry: string, photo: *MediaDiaryPhoto) ->
|
||||
return true
|
||||
}
|
||||
|
||||
// Lists the Diary files the library does not have and answers a checksum
|
||||
// of what decides the check: those files, whether their bytes are here,
|
||||
// and, when there are any, every day entry.
|
||||
// Lists the photos that have not moved and answers a checksum of what
|
||||
// decides the check: those photos, whether their bytes are here, the old
|
||||
// records of moved photos and, when there are Diary files, every day entry.
|
||||
MediaDiaryPhotosCollect :: () -> u64 {
|
||||
media_diary_photo_count = 0
|
||||
media_library_photo_count = 0
|
||||
owner := AppTextFromCString(storage_user_id_buffer(), 64)
|
||||
checksum := MediaDiaryMix(1469598103934665603, owner)
|
||||
statement: *void
|
||||
@@ -152,6 +208,29 @@ MediaDiaryPhotosCollect :: () -> u64 {
|
||||
}
|
||||
}
|
||||
SqliteFinalize(statement)
|
||||
if SqlitePrepareText(storage_db_handle(), MediaLibraryPhotosSQL, -1, *statement, null) == SQLITE_OK {
|
||||
unused bind_text(statement, 1, owner)
|
||||
while SqliteStep(statement) == SQLITE_ROW {
|
||||
hash := AppTextFromCString(SqliteColumnText(statement, 0), 65)
|
||||
path := MediaPath(hash, false)
|
||||
local := PackageFileSize(path) == SqliteColumnInt64(statement, 1)
|
||||
PackageFree(path)
|
||||
checksum = MediaDiaryMix(checksum, hash)
|
||||
checksum = MediaDiaryMix(checksum, ifx local then "1" else "0")
|
||||
if local && media_library_photo_count < MEDIA_DIARY_PHOTOS_MAX {
|
||||
unused AppCopyText(hash, media_library_photos[media_library_photo_count][:])
|
||||
media_library_photo_count += 1
|
||||
}
|
||||
}
|
||||
SqliteFinalize(statement)
|
||||
}
|
||||
if SqlitePrepareText(storage_db_handle(), MediaOldRecordsSQL, -1, *statement, null) == SQLITE_OK {
|
||||
unused bind_text(statement, 1, owner)
|
||||
while SqliteStep(statement) == SQLITE_ROW {
|
||||
checksum = MediaDiaryMix(checksum, AppTextFromCString(SqliteColumnText(statement, 0), 181))
|
||||
}
|
||||
SqliteFinalize(statement)
|
||||
}
|
||||
if media_diary_photo_count == 0 {
|
||||
return checksum
|
||||
}
|
||||
@@ -273,13 +352,11 @@ MediaDiaryEntriesRead :: () {
|
||||
}
|
||||
}
|
||||
|
||||
// Adds one photo an entry includes, unless the library has its record.
|
||||
// Moves one photo an entry includes, unless it moved already.
|
||||
MediaDiaryPhotoAdd :: (photo: *MediaDiaryPhoto) -> bool {
|
||||
hash := TextUntilNul(photo.hash[:])
|
||||
record_key := MediaRecordKey(hash)
|
||||
record := MediaRecordRead(record_key)
|
||||
record := MediaEntityRecord(hash)
|
||||
present := record.count > 0
|
||||
PackageFree(record_key)
|
||||
PackageFree(record)
|
||||
if present {
|
||||
return false
|
||||
@@ -304,7 +381,237 @@ MediaDiaryPhotoAdd :: (photo: *MediaDiaryPhoto) -> bool {
|
||||
return MediaAddBytes(data, addition).succeeded
|
||||
}
|
||||
|
||||
// Does a little of the work while a check is due or adding photos; true
|
||||
// Moves one photo of a released version's library whose bytes are here.
|
||||
MediaLibraryPhotoAdd :: (hash: string) -> bool {
|
||||
path := MediaPath(hash, false)
|
||||
data := PackageRead(path, DIARY_FILE_LIMIT)
|
||||
defer {
|
||||
PackageFree(path)
|
||||
PackageFree(data)
|
||||
}
|
||||
if !MediaDiaryBytesMatch(data, hash) {
|
||||
return false
|
||||
}
|
||||
return MediaAddBytes(data, MediaAddition.{.source = path}).succeeded
|
||||
}
|
||||
|
||||
// Fields a released version's library record has and the photo's entity
|
||||
// record lacks, as when another app moved the photo first: the entity
|
||||
// record takes them, so nothing the old record knew is lost. True when the
|
||||
// entity record changed; it goes out again before the old record may name
|
||||
// it.
|
||||
MediaEntityAddMissing :: (hash: string, legacy: string) -> bool {
|
||||
item := MediaParseLegacy(legacy)
|
||||
key := EntityPhotoKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
}
|
||||
if !item.valid || record.count == 0 {
|
||||
return false
|
||||
}
|
||||
names: [3]string = .["name", "day", "taken"]
|
||||
values: [3]string = .[TextUntilNul(item.name[:]), TextUntilNul(item.day[:]), TextUntilNul(item.taken[:])]
|
||||
updated := PackageText(record, "")
|
||||
changed := false
|
||||
for index: 0..2 {
|
||||
if FieldAt(updated, 0, names[index]) >= 0 || values[index].count == 0 {
|
||||
continue
|
||||
}
|
||||
quoted: Vec(u8)
|
||||
MediaJson(*quoted, values[index])
|
||||
value := BuilderFinish(quoted)
|
||||
next := MediaRecordWith(updated, names[index], value)
|
||||
PackageFree(value)
|
||||
if next.count > 0 {
|
||||
PackageFree(updated)
|
||||
updated = next
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if FieldAt(updated, 0, "trashed") < 0 {
|
||||
next := MediaRecordWith(updated, "trashed", ifx item.trashed then "true" else "false")
|
||||
if next.count > 0 {
|
||||
PackageFree(updated)
|
||||
updated = next
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if FieldAt(updated, 0, "added_at") < 0 && item.added > 0 {
|
||||
number: Vec(u8)
|
||||
BuilderPrint(*number, "%", item.added)
|
||||
value := BuilderFinish(number)
|
||||
next := MediaRecordWith(updated, "added_at", value)
|
||||
PackageFree(value)
|
||||
if next.count > 0 {
|
||||
PackageFree(updated)
|
||||
updated = next
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
written := changed && MediaRecordWrite(key, updated)
|
||||
PackageFree(updated)
|
||||
return written
|
||||
}
|
||||
|
||||
// The record with "photo" naming its entity record, keeping every field.
|
||||
MediaPointed :: (record: string, hash: string) -> string {
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "\"%\"", hash)
|
||||
quoted := BuilderFinish(out)
|
||||
defer { PackageFree(quoted) }
|
||||
return MediaRecordWith(record, "photo", quoted)
|
||||
}
|
||||
|
||||
// A photo from before copies frees its chunks once it moved: each becomes
|
||||
// one byte, so its room on the node shrinks with it.
|
||||
MediaShrinkChunks :: (entry: string, hash: string) {
|
||||
count := ReadNumber(entry, FieldAt(entry, 0, "count"))
|
||||
if !count.valid || count.value < 1.0 || count.value > 16384.0 {
|
||||
return
|
||||
}
|
||||
storage_settings_begin_write()
|
||||
defer { storage_settings_end_write() }
|
||||
for index: cast(s32)0..cast(s32)count.value - 1 {
|
||||
chunk := DiaryChunkKey(hash, index)
|
||||
unused CellRecordWrite(chunk, "-")
|
||||
PackageFree(chunk)
|
||||
}
|
||||
}
|
||||
|
||||
// The Diary file of a moved photo leaves this device once its library file
|
||||
// holds the same bytes; one that is the only copy here becomes the
|
||||
// library's file first.
|
||||
MediaDiaryFileMoved :: (name: string, hash: string, size: s64) {
|
||||
diary_path := DiaryStorePath(name)
|
||||
library_path := MediaPath(hash, false)
|
||||
defer {
|
||||
PackageFree(diary_path)
|
||||
PackageFree(library_path)
|
||||
}
|
||||
if !PathExists(diary_path) {
|
||||
return
|
||||
}
|
||||
library := PackageRead(library_path, DIARY_FILE_LIMIT)
|
||||
if library.count != size || !MediaDiaryBytesMatch(library, hash) {
|
||||
PackageFree(library)
|
||||
diary := PackageRead(diary_path, DIARY_FILE_LIMIT)
|
||||
directory := MediaDirectory()
|
||||
placed := MediaDiaryBytesMatch(diary, hash) && directory.count > 0 && storage_ensure_dir(directory) != 0 &&
|
||||
MediaPlaceFile(library_path, diary, diary_path)
|
||||
PackageFree(directory)
|
||||
PackageFree(diary)
|
||||
library = PackageRead(library_path, DIARY_FILE_LIMIT)
|
||||
if !placed {
|
||||
PackageFree(library)
|
||||
return
|
||||
}
|
||||
}
|
||||
same := library.count == size && MediaDiaryBytesMatch(library, hash)
|
||||
PackageFree(library)
|
||||
if same {
|
||||
unused RemoveFile(diary_path)
|
||||
diary_blob_generation += 1
|
||||
}
|
||||
}
|
||||
|
||||
// Diary files of photos whose entries name their entity record, on this
|
||||
// device still, as when another device moved them.
|
||||
MediaPointedFilesSQL :: #string SQL_END
|
||||
SELECT substr(key,17),json_extract(value,'$.hash'),json_extract(value,'$.size') FROM settings
|
||||
WHERE user_id=?1 AND key GLOB 'cell.diary.file.*' AND key NOT GLOB '*.json' AND json_valid(value)
|
||||
AND json_extract(value,'$.photo')=json_extract(value,'$.hash') AND json_type(value,'$.count') IS NULL
|
||||
AND EXISTS (SELECT 1 FROM settings e WHERE e.user_id=?1 AND e.key='entity.photos.'||json_extract(value,'$.hash'))
|
||||
ORDER BY key
|
||||
SQL_END;
|
||||
|
||||
// The Diary files of moved photos leave this device, a few per step.
|
||||
MediaPointedFilesMove :: () {
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(), MediaPointedFilesSQL, -1, *statement, null) != SQLITE_OK {
|
||||
return
|
||||
}
|
||||
defer { SqliteFinalize(statement) }
|
||||
unused bind_text(statement, 1, AppTextFromCString(storage_user_id_buffer(), 64))
|
||||
moved: s32 = 0
|
||||
while moved < MEDIA_DIARY_PHOTOS_PER_STEP && SqliteStep(statement) == SQLITE_ROW {
|
||||
name := PackageText(AppTextFromCString(SqliteColumnText(statement, 0), 201), "")
|
||||
hash := PackageText(AppTextFromCString(SqliteColumnText(statement, 1), 65), "")
|
||||
path := DiaryStorePath(name)
|
||||
if DiaryStoreNameValid(name) && MediaHashValid(hash) && PathExists(path) {
|
||||
MediaDiaryFileMoved(name, hash, SqliteColumnInt64(statement, 2))
|
||||
moved += 1
|
||||
}
|
||||
PackageFree(path)
|
||||
PackageFree(name)
|
||||
PackageFree(hash)
|
||||
}
|
||||
}
|
||||
|
||||
// Old records of moved photos name the entity record once the sync node
|
||||
// confirmed the photo and this device downloaded it back whole; then the
|
||||
// photo's old copies on this device go. A few records per step.
|
||||
MediaOldRecordsPoint :: () -> bool {
|
||||
sync_node: [256]u8
|
||||
if !SyncNodeAddress(storage_get_setting_text("sync_server_url"), sync_node[:]) {
|
||||
return false
|
||||
}
|
||||
node := TextUntilNul(sync_node[:])
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(), MediaOldRecordsSQL, -1, *statement, null) != SQLITE_OK {
|
||||
return false
|
||||
}
|
||||
defer { SqliteFinalize(statement) }
|
||||
unused bind_text(statement, 1, AppTextFromCString(storage_user_id_buffer(), 64))
|
||||
pointed: s32 = 0
|
||||
while pointed < MEDIA_DIARY_PHOTOS_PER_STEP && SqliteStep(statement) == SQLITE_ROW {
|
||||
key := PackageText(AppTextFromCString(SqliteColumnText(statement, 0), 181), "")
|
||||
entry := PackageText(AppTextFromCString(SqliteColumnText(statement, 1), 65536), "")
|
||||
hash := PackageText(AppTextFromCString(SqliteColumnText(statement, 2), 65), "")
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(entry)
|
||||
PackageFree(hash)
|
||||
}
|
||||
record := MediaEntityRecord(hash)
|
||||
ready := MediaHashValid(hash) && EntityPhotoConfirmed(hash, record, node) && EntityPhotoVerified(record, node)
|
||||
PackageFree(record)
|
||||
if !ready {
|
||||
continue
|
||||
}
|
||||
if MediaItemKeyHash(key).count == 64 && MediaEntityAddMissing(hash, entry) {
|
||||
continue
|
||||
}
|
||||
named := MediaPointed(entry, hash)
|
||||
defer { PackageFree(named) }
|
||||
diary_name := ifx key.count > 16 && key[:16] == "cell.diary.file." then key[16:] else ""
|
||||
written := false
|
||||
if diary_name.count > 0 {
|
||||
written = named.count > 0 && CellRecordWrite(key, named)
|
||||
} else {
|
||||
written = named.count > 0 && MediaRecordWrite(key, named)
|
||||
}
|
||||
if !written {
|
||||
continue
|
||||
}
|
||||
pointed += 1
|
||||
if diary_name.count == 0 {
|
||||
continue
|
||||
}
|
||||
if FieldAt(entry, 0, "count") >= 0 {
|
||||
MediaShrinkChunks(entry, hash)
|
||||
} else {
|
||||
size := ReadNumber(entry, FieldAt(entry, 0, "size"))
|
||||
if size.valid {
|
||||
MediaDiaryFileMoved(diary_name, hash, cast(s64)size.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
return pointed > 0
|
||||
}
|
||||
|
||||
// Does a little of the work while a check is due or moving photos; true
|
||||
// while more is waiting.
|
||||
MediaDiaryPhotosStep :: () -> bool {
|
||||
owner := AppTextFromCString(storage_user_id_buffer(), 64)
|
||||
@@ -318,7 +625,7 @@ MediaDiaryPhotosStep :: () -> bool {
|
||||
media_diary_generation = diary_blob_generation
|
||||
media_diary_due = true
|
||||
}
|
||||
if owner.count == 0 || DataTemporary() || storage_db_handle() == null {
|
||||
if owner.count == 0 || DataTemporary() || storage_db_handle() == null || !MediaMovesAllowed() {
|
||||
media_diary_adding = false
|
||||
return false
|
||||
}
|
||||
@@ -332,10 +639,20 @@ MediaDiaryPhotosStep :: () -> bool {
|
||||
added += 1
|
||||
}
|
||||
}
|
||||
if media_diary_next < media_diary_photo_count {
|
||||
while media_library_next < media_library_photo_count && added < MEDIA_DIARY_PHOTOS_PER_STEP {
|
||||
hash := TextUntilNul(media_library_photos[media_library_next][:])
|
||||
media_library_next += 1
|
||||
unused MediaLibraryPhotoAdd(hash)
|
||||
added += 1
|
||||
}
|
||||
if media_diary_next < media_diary_photo_count || media_library_next < media_library_photo_count {
|
||||
return true
|
||||
}
|
||||
// What is left waits for a change: its bytes, or an entry naming it.
|
||||
if MediaOldRecordsPoint() {
|
||||
return true
|
||||
}
|
||||
// What is left waits for a change: its bytes, an entry naming it,
|
||||
// or the node confirming a moved photo.
|
||||
media_diary_adding = false
|
||||
media_diary_seen = MediaDiaryPhotosCollect()
|
||||
media_diary_seen_valid = true
|
||||
@@ -345,14 +662,23 @@ MediaDiaryPhotosStep :: () -> bool {
|
||||
return false
|
||||
}
|
||||
media_diary_due = false
|
||||
MediaPointedFilesMove()
|
||||
seen := MediaDiaryPhotosCollect()
|
||||
if media_diary_photo_count == 0 || (media_diary_seen_valid && seen == media_diary_seen) {
|
||||
media_diary_seen = seen
|
||||
media_diary_seen_valid = true
|
||||
if media_diary_seen_valid && seen == media_diary_seen {
|
||||
// Nothing new to move. Moved photos the node confirmed since may
|
||||
// name their old records now, and those records go out.
|
||||
if MediaOldRecordsPoint() {
|
||||
media_diary_due = true
|
||||
}
|
||||
return false
|
||||
}
|
||||
MediaDiaryEntriesRead()
|
||||
media_diary_seen = seen
|
||||
media_diary_seen_valid = true
|
||||
if media_diary_photo_count > 0 {
|
||||
MediaDiaryEntriesRead()
|
||||
}
|
||||
media_diary_adding = true
|
||||
media_diary_next = 0
|
||||
media_library_next = 0
|
||||
return true
|
||||
}
|
||||
@@ -324,3 +324,90 @@ MediaOrientationOf :: (data: string, format: string) -> s32 {
|
||||
}
|
||||
return cast(s32)value
|
||||
}
|
||||
|
||||
// A picture's size in pixels, from its header alone.
|
||||
MediaSize :: struct {
|
||||
valid: bool
|
||||
width: s64
|
||||
height: s64
|
||||
}
|
||||
|
||||
// A JPEG's frame size, from its first start-of-frame segment.
|
||||
MediaJpegSize :: (data: string) -> MediaSize {
|
||||
at: s64 = 2
|
||||
while at + 4 <= data.count {
|
||||
if data[at] != cast(u8)255 {
|
||||
return MediaSize.{}
|
||||
}
|
||||
marker := data[at + 1]
|
||||
if marker == cast(u8)217 || marker == cast(u8)218 {
|
||||
return MediaSize.{}
|
||||
}
|
||||
if marker == cast(u8)255 {
|
||||
at += 1
|
||||
continue
|
||||
}
|
||||
if marker == cast(u8)1 || (marker >= cast(u8)208 && marker <= cast(u8)215) {
|
||||
at += 2
|
||||
continue
|
||||
}
|
||||
length := MediaNumber(data, at + 2, 2, false)
|
||||
if length < 2 || at + 2 + length > data.count {
|
||||
return MediaSize.{}
|
||||
}
|
||||
// SOF0 to SOF15, except DHT (196), JPG (200) and DAC (204).
|
||||
frame := marker >= cast(u8)192 && marker <= cast(u8)207 && marker != cast(u8)196 &&
|
||||
marker != cast(u8)200 && marker != cast(u8)204
|
||||
if frame && length >= 7 {
|
||||
return MediaSize.{.valid = true, .width = MediaNumber(data, at + 7, 2, false),
|
||||
.height = MediaNumber(data, at + 5, 2, false)}
|
||||
}
|
||||
at += 2 + length
|
||||
}
|
||||
return MediaSize.{}
|
||||
}
|
||||
|
||||
// A WebP's canvas: lossy (VP8), lossless (VP8L) or extended (VP8X).
|
||||
MediaWebpSize :: (data: string) -> MediaSize {
|
||||
if data.count < 30 {
|
||||
return MediaSize.{}
|
||||
}
|
||||
kind := data[12:16]
|
||||
if kind == "VP8 " && data[23] == cast(u8)157 && data[24] == cast(u8)1 && data[25] == cast(u8)42 {
|
||||
return MediaSize.{.valid = true, .width = MediaNumber(data, 26, 2, true) & 16383,
|
||||
.height = MediaNumber(data, 28, 2, true) & 16383}
|
||||
}
|
||||
if kind == "VP8L" && data[20] == cast(u8)47 {
|
||||
bits := MediaNumber(data, 21, 4, true)
|
||||
return MediaSize.{.valid = true, .width = (bits & 16383) + 1, .height = ((bits >> 14) & 16383) + 1}
|
||||
}
|
||||
if kind == "VP8X" {
|
||||
return MediaSize.{.valid = true, .width = MediaNumber(data, 24, 3, true) + 1,
|
||||
.height = MediaNumber(data, 27, 3, true) + 1}
|
||||
}
|
||||
return MediaSize.{}
|
||||
}
|
||||
|
||||
// The picture's size as it shows: turned when the camera says its pixels
|
||||
// lie on their side (orientations 5 to 8).
|
||||
MediaSizeOf :: (data: string, format: string) -> MediaSize {
|
||||
size: MediaSize
|
||||
if format == "png" && data.count >= 24 && data[12:16] == "IHDR" {
|
||||
size = MediaSize.{.valid = true, .width = MediaNumber(data, 16, 4, false),
|
||||
.height = MediaNumber(data, 20, 4, false)}
|
||||
} else if format == "gif" && data.count >= 10 {
|
||||
size = MediaSize.{.valid = true, .width = MediaNumber(data, 6, 2, true),
|
||||
.height = MediaNumber(data, 8, 2, true)}
|
||||
} else if format == "jpg" {
|
||||
size = MediaJpegSize(data)
|
||||
} else if format == "webp" {
|
||||
size = MediaWebpSize(data)
|
||||
}
|
||||
if !size.valid || size.width < 1 || size.height < 1 {
|
||||
return MediaSize.{}
|
||||
}
|
||||
if MediaOrientationOf(data, format) >= 5 {
|
||||
return MediaSize.{.valid = true, .width = size.height, .height = size.width}
|
||||
}
|
||||
return size
|
||||
}
|
||||
+347
-118
@@ -4,21 +4,25 @@
|
||||
// is its interface; the library belongs to the account, so its photos stay
|
||||
// when an app that added them is removed.
|
||||
//
|
||||
// Records sync in their own collection, private.inbe.v1.media, which older
|
||||
// versions skip (storage/media_records.zi):
|
||||
// Each photo is a record of the account's entity data, entity.photos.<sha256>
|
||||
// (entity_photos.zi), which every app of the account shares: Diary embeds
|
||||
// the same photo, and other apps such as Photos read and write the same
|
||||
// record. Its bytes travel as the entity data's sealed chunks
|
||||
// (diary_blobs.zi), so the same picture is stored once on each node. Files
|
||||
// live per account under media/<account>/<sha256> and <sha256>.preview,
|
||||
// beside the Diary's folder. Previews download on every device; an original
|
||||
// only where it is wanted, such as when Photos opens it.
|
||||
//
|
||||
// Released versions kept the library in private.inbe.v1.media
|
||||
// (storage/media_records.zi), which they still read through 2027-10-24:
|
||||
//
|
||||
// cell.media.<sha256> {"hash","size","type","name","day","taken",
|
||||
// "added","trashed"[,"blob","key"]}
|
||||
// cell.media.preview.<sha256> {"hash","size","type"[,"blob","key"]}
|
||||
// "added","trashed"[,"blob","key"][,"photo"]}
|
||||
// cell.media.preview.<sha256> {"hash","size","type"[,"blob","key"][,"photo"]}
|
||||
//
|
||||
// "day" is the capture day on the camera's clock (or the day the photo was
|
||||
// added), "taken" the capture time, with its offset when the camera wrote
|
||||
// one. The bytes travel as the same sealed copies as Diary photos
|
||||
// (diary_records.zi, diary_blobs.zi): a key made from the account key and
|
||||
// the file's hash, so the same picture is one copy on each node. Files live
|
||||
// per account under media/<account>/<sha256> and <sha256>.preview, beside
|
||||
// the Diary's folder. Previews download on every device; an original only
|
||||
// where it is wanted, such as when Photos opens it.
|
||||
// A photo there without an entity record is listed from it until it moves
|
||||
// (media_diary_photos.zi): its entity record takes its fields, and its old
|
||||
// copy goes once the node has the new one.
|
||||
#import "file_linux"
|
||||
#import "byte_text_linux"
|
||||
#import "vec"
|
||||
@@ -29,6 +33,8 @@
|
||||
#import, file "diary_records.zi";
|
||||
#import, file "diary_store.zi";
|
||||
#import, file "media_metadata.zi";
|
||||
#import, file "entity_photos.zi";
|
||||
#import, file "../storage/entity_records.zi";
|
||||
#import, file "package_files.zi";
|
||||
#import, file "../storage/media_records.zi";
|
||||
#import, file "../storage/cell_records.zi";
|
||||
@@ -72,6 +78,8 @@ MediaItem :: struct {
|
||||
taken: [26]u8
|
||||
added: s64
|
||||
trashed: bool
|
||||
// An entity record; otherwise a released version's library record.
|
||||
entity: bool
|
||||
}
|
||||
|
||||
MediaImport :: struct {
|
||||
@@ -119,9 +127,10 @@ MediaPreviewKey :: (hash: string) -> string {
|
||||
return PackageText(MEDIA_PREVIEW_PREFIX, hash)
|
||||
}
|
||||
|
||||
// A record of the library, or empty.
|
||||
// A record of the library: an entity record, or a released version's, or
|
||||
// empty.
|
||||
MediaRecordRead :: (key: string) -> string {
|
||||
if !MediaRecordKeyAccepted(key) || storage_db_handle() == null {
|
||||
if (!MediaRecordKeyAccepted(key) && !EntityPhotoKeyAccepted(key)) || storage_db_handle() == null {
|
||||
return ""
|
||||
}
|
||||
statement: *void
|
||||
@@ -139,9 +148,10 @@ MediaRecordRead :: (key: string) -> string {
|
||||
return PackageText(AppTextFromCString(SqliteColumnText(statement, 0), 65536), "")
|
||||
}
|
||||
|
||||
// Saves a record of the library; it syncs in the library's collection.
|
||||
// Saves a record of the library; it syncs in its record's collection.
|
||||
MediaRecordWrite :: (key: string, value: string) -> bool {
|
||||
if !MediaRecordKeyAccepted(key) || value.count == 0 || value.count >= 65536 {
|
||||
if (!MediaRecordKeyAccepted(key) && !EntityPhotoKeyAccepted(key)) || value.count == 0 ||
|
||||
value.count >= 65536 {
|
||||
return false
|
||||
}
|
||||
storage_set_setting_text(key, value)
|
||||
@@ -212,7 +222,77 @@ MediaJson :: (out: *Vec(u8), value: string) {
|
||||
BuilderPrint(out, "\"")
|
||||
}
|
||||
|
||||
// A day as YYYY-MM-DD from seconds since 1970 in UTC.
|
||||
MediaDayOfSeconds :: (seconds: s64, output: []u8) -> bool {
|
||||
days := seconds / 86400
|
||||
if seconds < 0 && seconds % 86400 != 0 {
|
||||
days -= 1
|
||||
}
|
||||
// Days to a civil date (proleptic Gregorian).
|
||||
shifted := days + 719468
|
||||
era := ifx shifted >= 0 then shifted / 146097 else (shifted - 146096) / 146097
|
||||
day_of_era := shifted - era * 146097
|
||||
year_of_era := (day_of_era - day_of_era / 1460 + day_of_era / 36524 - day_of_era / 146096) / 365
|
||||
day_of_year := day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100)
|
||||
month_index := (5 * day_of_year + 2) / 153
|
||||
day := day_of_year - (153 * month_index + 2) / 5 + 1
|
||||
month := ifx month_index < 10 then month_index + 3 else month_index - 9
|
||||
year := year_of_era + era * 400 + ifx month <= 2 then cast(s64)1 else cast(s64)0
|
||||
if year < 1000 || year > 9999 {
|
||||
return false
|
||||
}
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "%-", year)
|
||||
BuilderPrint(*out, "%-", MediaTwo(cast(s32)month))
|
||||
BuilderPrint(*out, "%", MediaTwo(cast(s32)day))
|
||||
value := BuilderFinish(out)
|
||||
defer { PackageFree(value) }
|
||||
return AppCopyText(value, output)
|
||||
}
|
||||
|
||||
// A photo's entity record as the library lists it. A record another app
|
||||
// wrote may lack the capture day; its capture time's UTC day stands in.
|
||||
MediaParseEntity :: (record: string) -> MediaItem {
|
||||
item: MediaItem
|
||||
content := EntityPhotoContent(record)
|
||||
format := TextUntilNul(content.format[:])
|
||||
if !content.valid || format.count == 0 {
|
||||
return item
|
||||
}
|
||||
item.hash = content.hash
|
||||
item.size = content.size
|
||||
unused AppCopyText(format, item.format[:])
|
||||
if ReadStringText(record, FieldAt(record, 0, "day"), item.day[:]) != 10 ||
|
||||
!MediaDayValid(TextFromBytes(item.day[:10])) {
|
||||
taken_at := ReadNumber(record, FieldAt(record, 0, "taken_at"))
|
||||
if !taken_at.valid || !MediaDayOfSeconds(cast(s64)taken_at.value, item.day[:]) {
|
||||
return MediaItem.{}
|
||||
}
|
||||
}
|
||||
unused ReadStringText(record, FieldAt(record, 0, "name"), item.name[:])
|
||||
unused ReadStringText(record, FieldAt(record, 0, "taken"), item.taken[:])
|
||||
added := ReadNumber(record, FieldAt(record, 0, "added_at"))
|
||||
if added.valid {
|
||||
item.added = cast(s64)added.value
|
||||
}
|
||||
trashed := FieldAt(record, 0, "trashed")
|
||||
item.trashed = MatchLiteral(record, trashed, "true")
|
||||
item.entity = true
|
||||
item.valid = true
|
||||
return item
|
||||
}
|
||||
|
||||
// A library record of either kind.
|
||||
MediaParse :: (record: string) -> MediaItem {
|
||||
if FieldAt(record, 0, "added_at") >= 0 || FieldAt(record, 0, "blobs") >= 0 ||
|
||||
FieldAt(record, 0, "taken_at") >= 0 {
|
||||
return MediaParseEntity(record)
|
||||
}
|
||||
return MediaParseLegacy(record)
|
||||
}
|
||||
|
||||
// A released version's library record.
|
||||
MediaParseLegacy :: (record: string) -> MediaItem {
|
||||
item: MediaItem
|
||||
media := DiaryMediaParse(record)
|
||||
if !media.valid {
|
||||
@@ -236,23 +316,46 @@ MediaParse :: (record: string) -> MediaItem {
|
||||
return item
|
||||
}
|
||||
|
||||
// The library's photo: its entity record, or a released version's record
|
||||
// while the photo has none.
|
||||
MediaRead :: (hash: string) -> MediaItem {
|
||||
if !MediaHashValid(hash) {
|
||||
return MediaItem.{}
|
||||
}
|
||||
entity_key := EntityPhotoKey(hash)
|
||||
entity_record := MediaRecordRead(entity_key)
|
||||
PackageFree(entity_key)
|
||||
if entity_record.count > 0 {
|
||||
item := MediaParseEntity(entity_record)
|
||||
PackageFree(entity_record)
|
||||
if item.valid && TextFromBytes(item.hash[:64]) != hash {
|
||||
return MediaItem.{}
|
||||
}
|
||||
return item
|
||||
}
|
||||
key := MediaRecordKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
}
|
||||
item := MediaParse(record)
|
||||
item := MediaParseLegacy(record)
|
||||
if item.valid && TextFromBytes(item.hash[:64]) != hash {
|
||||
return MediaItem.{}
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
// The photo's entity record, or empty.
|
||||
MediaEntityRecord :: (hash: string) -> string {
|
||||
if !MediaHashValid(hash) {
|
||||
return ""
|
||||
}
|
||||
key := EntityPhotoKey(hash)
|
||||
defer { PackageFree(key) }
|
||||
return MediaRecordRead(key)
|
||||
}
|
||||
|
||||
media_two: [3]u8;
|
||||
|
||||
MediaTwo :: (value: s32) -> string {
|
||||
@@ -395,28 +498,6 @@ MediaRecordWith :: (record: string, field: string, value: string) -> string {
|
||||
return PackageText(AppTextFromCString(SqliteColumnText(statement, 0), 65536), "")
|
||||
}
|
||||
|
||||
// The record once its sealed copy is on a node: it names the copy's address
|
||||
// and key, so the account's other devices can download it.
|
||||
MediaRecordSetCopy :: (key: string, record: string, blob: string, key_hex: string) -> bool {
|
||||
if !MediaHashValid(blob) || !MediaHashValid(key_hex) {
|
||||
return false
|
||||
}
|
||||
blob_text: Vec(u8)
|
||||
BuilderPrint(*blob_text, "\"%\"", blob)
|
||||
quoted_blob := BuilderFinish(blob_text)
|
||||
with_blob := MediaRecordWith(record, "blob", quoted_blob)
|
||||
key_text: Vec(u8)
|
||||
BuilderPrint(*key_text, "\"%\"", key_hex)
|
||||
quoted_key := BuilderFinish(key_text)
|
||||
named := MediaRecordWith(with_blob, "key", quoted_key)
|
||||
written := named.count > 0 && MediaRecordWrite(key, named)
|
||||
PackageFree(quoted_blob)
|
||||
PackageFree(with_blob)
|
||||
PackageFree(quoted_key)
|
||||
PackageFree(named)
|
||||
return written
|
||||
}
|
||||
|
||||
// How a photo joins the library.
|
||||
MediaAddition :: struct {
|
||||
// The name the photo came with; folders are dropped.
|
||||
@@ -463,8 +544,98 @@ MediaImportBytes :: (data: string, name: string) -> MediaImport {
|
||||
return MediaAddBytes(data, MediaAddition.{.name = name, .restore = true})
|
||||
}
|
||||
|
||||
// A preview this device made for a photo: its file is written, and the
|
||||
// photo's record names it.
|
||||
MediaPreviewMade :: struct {
|
||||
valid: bool
|
||||
hash: [65]u8
|
||||
size: s64
|
||||
format: [8]u8
|
||||
}
|
||||
|
||||
// The capture time as seconds since 1970, read as UTC when the camera wrote
|
||||
// no offset; -1 when it is no time.
|
||||
MediaTakenAt :: (taken: string) -> s64 {
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(), "SELECT COALESCE(CAST(strftime('%s',?1) AS INTEGER),-1)", -1,
|
||||
*statement, null) != SQLITE_OK {
|
||||
return -1
|
||||
}
|
||||
defer { SqliteFinalize(statement) }
|
||||
unused bind_text(statement, 1, taken)
|
||||
if SqliteStep(statement) != SQLITE_ROW {
|
||||
return -1
|
||||
}
|
||||
return SqliteColumnInt64(statement, 0)
|
||||
}
|
||||
|
||||
// What a photo's entity record says about it besides its bytes.
|
||||
MediaEntityFields :: struct {
|
||||
name: string
|
||||
day: string
|
||||
taken: string
|
||||
added: s64
|
||||
trashed: bool
|
||||
capture: bool
|
||||
preview: MediaPreviewMade
|
||||
}
|
||||
|
||||
// A new entity record for the photo's bytes.
|
||||
MediaEntityEntry :: (hash: string, data: string, format: string, fields: MediaEntityFields) -> string {
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "{\"hash\":\"%\",\"size\":%,\"type\":\"%\"", hash, data.count, EntityTypeOfFormat(format))
|
||||
taken_at := MediaTakenAt(fields.taken)
|
||||
if taken_at >= 0 {
|
||||
BuilderPrint(*out, ",\"taken_at\":%", taken_at)
|
||||
}
|
||||
size := MediaSizeOf(data, format)
|
||||
if size.valid {
|
||||
BuilderPrint(*out, ",\"width\":%,\"height\":%", size.width, size.height)
|
||||
}
|
||||
if fields.preview.valid {
|
||||
BuilderPrint(*out, ",\"preview\":{\"hash\":\"%\",\"size\":%,\"type\":\"%\"}",
|
||||
TextUntilNul(fields.preview.hash[:]), fields.preview.size,
|
||||
EntityTypeOfFormat(TextUntilNul(fields.preview.format[:])))
|
||||
}
|
||||
BuilderPrint(*out, ",\"added_at\":%,\"name\":", fields.added)
|
||||
MediaJson(*out, MediaName(fields.name))
|
||||
BuilderPrint(*out, ",\"trashed\":%,\"day\":\"%\",\"taken\":", ifx fields.trashed then "true" else "false",
|
||||
fields.day)
|
||||
MediaJson(*out, fields.taken)
|
||||
BuilderPrint(*out, ",\"capture\":%}", ifx fields.capture then "true" else "false")
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
// A released version's preview of the photo, when its file is here, as the
|
||||
// photo's preview: the same bytes, so it is not made again.
|
||||
MediaLegacyPreview :: (hash: string) -> MediaPreviewMade {
|
||||
made: MediaPreviewMade
|
||||
key := MediaPreviewKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
path := MediaPath(hash, true)
|
||||
data := PackageRead(path, DIARY_FILE_LIMIT)
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
PackageFree(path)
|
||||
PackageFree(data)
|
||||
}
|
||||
media := DiaryMediaParse(record)
|
||||
format := DiaryImageFormat(data)
|
||||
if format.count == 0 || !DiaryMediaMatches(media, data) {
|
||||
return made
|
||||
}
|
||||
made.hash = media.hash
|
||||
made.size = media.size
|
||||
unused AppCopyText(format, made.format[:])
|
||||
made.valid = true
|
||||
return made
|
||||
}
|
||||
|
||||
// Adds the photo's bytes to the library once. A photo it already has keeps
|
||||
// its record, and leaves Trash only when the addition says so.
|
||||
// its record, and leaves Trash only when the addition says so. A photo a
|
||||
// released version's library keeps gets its entity record now, with that
|
||||
// record's name, day, Trash and the time it was added.
|
||||
MediaAddBytes :: (data: string, addition: MediaAddition) -> MediaImport {
|
||||
result: MediaImport
|
||||
if DataTemporary() || data.count <= 0 || data.count > DIARY_FILE_LIMIT {
|
||||
@@ -487,17 +658,17 @@ MediaAddBytes :: (data: string, addition: MediaAddition) -> MediaImport {
|
||||
!MediaPlaceFile(path, data, addition.source) {
|
||||
return result
|
||||
}
|
||||
key := MediaRecordKey(hash)
|
||||
key := EntityPhotoKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
}
|
||||
existing := MediaParse(record)
|
||||
existing := MediaParseEntity(record)
|
||||
if existing.valid {
|
||||
result.existed = true
|
||||
if existing.trashed && addition.restore {
|
||||
restored := MediaRecordWith(record, "trashed", "0")
|
||||
restored := MediaRecordWith(record, "trashed", "false")
|
||||
written := restored.count > 0 && MediaRecordWrite(key, restored)
|
||||
PackageFree(restored)
|
||||
if !written {
|
||||
@@ -509,27 +680,48 @@ MediaAddBytes :: (data: string, addition: MediaAddition) -> MediaImport {
|
||||
result.succeeded = true
|
||||
return result
|
||||
}
|
||||
legacy_key := MediaRecordKey(hash)
|
||||
legacy_record := MediaRecordRead(legacy_key)
|
||||
legacy := MediaParseLegacy(legacy_record)
|
||||
legacy_capture := ReadNumber(legacy_record, FieldAt(legacy_record, 0, "capture"))
|
||||
PackageFree(legacy_key)
|
||||
PackageFree(legacy_record)
|
||||
day: [11]u8
|
||||
taken: [26]u8
|
||||
fields: MediaEntityFields
|
||||
capture_data := ifx addition.capture_source.count > 0 then addition.capture_source else data
|
||||
capture_format := ifx addition.capture_source.count > 0 then DiaryImageFormat(capture_data) else format
|
||||
if !MediaWhen(capture_data, capture_format, addition.day, day[:], taken[:]) {
|
||||
return result
|
||||
}
|
||||
MediaWritePreview(hash, data, format)
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "{\"hash\":\"%\",\"size\":%,\"type\":\"%\",\"name\":", hash, data.count, format)
|
||||
MediaJson(*out, MediaName(addition.name))
|
||||
capture := MediaCaptureOf(capture_data, capture_format)
|
||||
BuilderPrint(*out, ",\"day\":\"%\",\"taken\":\"%\",\"added\":%,\"capture\":%,\"trashed\":0}",
|
||||
TextUntilNul(day[:]), TextUntilNul(taken[:]), CellRecordClock() / 1000000,
|
||||
ifx capture.valid && capture.year >= 1000 then 1 else 0)
|
||||
entry := BuilderFinish(out)
|
||||
if legacy.valid && TextFromBytes(legacy.hash[:64]) == hash {
|
||||
result.existed = true
|
||||
fields.name = TextUntilNul(legacy.name[:])
|
||||
fields.day = TextUntilNul(legacy.day[:])
|
||||
fields.taken = TextUntilNul(legacy.taken[:])
|
||||
fields.added = legacy.added
|
||||
fields.trashed = legacy.trashed && !addition.restore
|
||||
fields.capture = ifx legacy_capture.valid then legacy_capture.value != 0.0 else capture.valid && capture.year >= 1000
|
||||
fields.preview = MediaLegacyPreview(hash)
|
||||
} else {
|
||||
if !MediaWhen(capture_data, capture_format, addition.day, day[:], taken[:]) {
|
||||
return result
|
||||
}
|
||||
fields.name = addition.name
|
||||
fields.day = TextUntilNul(day[:])
|
||||
fields.taken = TextUntilNul(taken[:])
|
||||
fields.added = CellRecordClock() / 1000000
|
||||
fields.capture = capture.valid && capture.year >= 1000
|
||||
}
|
||||
if !fields.preview.valid {
|
||||
fields.preview = MediaWritePreview(hash, data, format)
|
||||
}
|
||||
entry := MediaEntityEntry(hash, data, format, fields)
|
||||
defer { PackageFree(entry) }
|
||||
if !MediaRecordWrite(key, entry) {
|
||||
return result
|
||||
}
|
||||
AchievementPhotoImported(hash)
|
||||
if !legacy.valid {
|
||||
AchievementPhotoImported(hash)
|
||||
}
|
||||
MediaAssetsChanged()
|
||||
sync_web_storage()
|
||||
result.succeeded = true
|
||||
@@ -538,7 +730,8 @@ MediaAddBytes :: (data: string, addition: MediaAddition) -> MediaImport {
|
||||
|
||||
// A preview turns the photo upright and makes it small. A small upright
|
||||
// photo is its own preview and gets none.
|
||||
MediaWritePreview :: (hash: string, data: string, source_format: string) {
|
||||
MediaWritePreview :: (hash: string, data: string, source_format: string) -> MediaPreviewMade {
|
||||
made: MediaPreviewMade
|
||||
orientation := MediaOrientationOf(data, source_format)
|
||||
file_type := PackageText(".", source_format)
|
||||
preview := ImagePreview(data, file_type, MEDIA_PREVIEW_EDGE, orientation, MEDIA_PREVIEW_QUALITY)
|
||||
@@ -548,24 +741,19 @@ MediaWritePreview :: (hash: string, data: string, source_format: string) {
|
||||
}
|
||||
format := DiaryImageFormat(preview)
|
||||
if format.count == 0 || (orientation == 1 && preview.count >= data.count) {
|
||||
return
|
||||
return made
|
||||
}
|
||||
path := MediaPath(hash, true)
|
||||
defer { PackageFree(path) }
|
||||
if !MediaWriteFile(path, preview) {
|
||||
return
|
||||
return made
|
||||
}
|
||||
descriptor := cast(*TextDescriptor)(*preview)
|
||||
preview_hash: [65]u8
|
||||
storage_sha256_hex(descriptor.data, preview.count, *preview_hash[0])
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "{\"hash\":\"%\",\"size\":%,\"type\":\"%\"}",
|
||||
TextFromCString(*preview_hash[0]), preview.count, format)
|
||||
entry := BuilderFinish(out)
|
||||
key := MediaPreviewKey(hash)
|
||||
unused MediaRecordWrite(key, entry)
|
||||
PackageFree(entry)
|
||||
PackageFree(key)
|
||||
storage_sha256_hex(descriptor.data, preview.count, *made.hash[0])
|
||||
made.size = preview.count
|
||||
unused AppCopyText(format, made.format[:])
|
||||
made.valid = true
|
||||
return made
|
||||
}
|
||||
|
||||
// Adds a file the person picked. Only its bytes and its name are kept.
|
||||
@@ -613,13 +801,28 @@ MediaPlaceHash :: (place: string) -> string {
|
||||
|
||||
// Queries.
|
||||
|
||||
// Entity records, and a released version's records of photos that have
|
||||
// none yet. A record another app wrote may lack the capture day and time;
|
||||
// its capture time's UTC day and time stand in.
|
||||
MediaQuerySQL :: #string SQL_END
|
||||
SELECT substr(key,12),json_extract(value,'$.day') FROM settings
|
||||
WHERE user_id=?1 AND key GLOB 'cell.media.*' AND length(key)=75
|
||||
AND substr(key,12) NOT GLOB '*[^0-9a-f]*' AND json_valid(value)
|
||||
AND (?2='' OR json_extract(value,'$.day')=?2)
|
||||
AND (CASE WHEN COALESCE(json_extract(value,'$.trashed'),0)=0 THEN 0 ELSE 1 END)=?3
|
||||
ORDER BY json_extract(value,'$.taken') DESC,key DESC
|
||||
SELECT hash,day FROM (
|
||||
SELECT substr(key,15) AS hash,
|
||||
COALESCE(json_extract(value,'$.day'),date(json_extract(value,'$.taken_at'),'unixepoch')) AS day,
|
||||
COALESCE(json_extract(value,'$.taken'),
|
||||
strftime('%Y-%m-%dT%H:%M:%S',json_extract(value,'$.taken_at'),'unixepoch')) AS taken,
|
||||
COALESCE(json_extract(value,'$.trashed'),0) AS trashed
|
||||
FROM settings WHERE user_id=?1 AND key GLOB 'entity.photos.*' AND length(key)=78
|
||||
AND substr(key,15) NOT GLOB '*[^0-9a-f]*' AND json_valid(value)
|
||||
AND json_extract(value,'$.type') IN ('image/png','image/jpeg','image/gif','image/webp')
|
||||
UNION ALL
|
||||
SELECT substr(l.key,12),json_extract(l.value,'$.day'),json_extract(l.value,'$.taken'),
|
||||
COALESCE(json_extract(l.value,'$.trashed'),0)
|
||||
FROM settings l WHERE l.user_id=?1 AND l.key GLOB 'cell.media.*' AND length(l.key)=75
|
||||
AND substr(l.key,12) NOT GLOB '*[^0-9a-f]*' AND json_valid(l.value)
|
||||
AND NOT EXISTS (SELECT 1 FROM settings e WHERE e.user_id=?1 AND e.key='entity.photos.'||substr(l.key,12))
|
||||
)
|
||||
WHERE (?2='' OR day=?2) AND (CASE WHEN trashed=0 THEN 0 ELSE 1 END)=?3
|
||||
ORDER BY taken DESC,hash DESC
|
||||
LIMIT ?4
|
||||
SQL_END;
|
||||
|
||||
@@ -780,25 +983,8 @@ MediaAssetsChanged :: () {
|
||||
diary_blob_generation += 1
|
||||
}
|
||||
|
||||
// The local file's format when it holds as many bytes as its record names.
|
||||
MediaLocalFormat :: (hash: string, preview: bool) -> string {
|
||||
key := ifx preview then MediaPreviewKey(hash) else MediaRecordKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
}
|
||||
media := DiaryMediaParse(record)
|
||||
format: [8]u8
|
||||
if !media.valid || ReadStringText(record, FieldAt(record, 0, "type"), format[:]) <= 0 {
|
||||
return ""
|
||||
}
|
||||
path := MediaPath(hash, preview)
|
||||
defer { PackageFree(path) }
|
||||
if PackageFileSize(path) != media.size {
|
||||
return ""
|
||||
}
|
||||
value := TextUntilNul(format[:])
|
||||
// A format word as a constant, or empty.
|
||||
MediaFormatLiteral :: (value: string) -> string {
|
||||
if value == "png" {
|
||||
return "png"
|
||||
}
|
||||
@@ -814,6 +1000,45 @@ MediaLocalFormat :: (hash: string, preview: bool) -> string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// What the photo's record says of its original or its preview: the hash,
|
||||
// size and format the file must have.
|
||||
MediaContentOf :: (hash: string, preview: bool) -> EntityContent {
|
||||
entity := MediaEntityRecord(hash)
|
||||
defer { PackageFree(entity) }
|
||||
if entity.count > 0 {
|
||||
return ifx preview then EntityPreviewContent(entity) else EntityPhotoContent(entity)
|
||||
}
|
||||
key := ifx preview then MediaPreviewKey(hash) else MediaRecordKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
}
|
||||
media := DiaryMediaParse(record)
|
||||
content: EntityContent
|
||||
if !media.valid || ReadStringText(record, FieldAt(record, 0, "type"), content.format[:]) <= 0 {
|
||||
return content
|
||||
}
|
||||
content.hash = media.hash
|
||||
content.size = media.size
|
||||
content.valid = true
|
||||
return content
|
||||
}
|
||||
|
||||
// The local file's format when it holds as many bytes as its record names.
|
||||
MediaLocalFormat :: (hash: string, preview: bool) -> string {
|
||||
content := MediaContentOf(hash, preview)
|
||||
if !content.valid {
|
||||
return ""
|
||||
}
|
||||
path := MediaPath(hash, preview)
|
||||
defer { PackageFree(path) }
|
||||
if PackageFileSize(path) != content.size {
|
||||
return ""
|
||||
}
|
||||
return MediaFormatLiteral(TextUntilNul(content.format[:]))
|
||||
}
|
||||
|
||||
MediaAssetLookup :: (hash: string, original: bool) -> string {
|
||||
out: Vec(u8)
|
||||
if original {
|
||||
@@ -931,15 +1156,11 @@ MediaAssetView :: (path: string) -> AssetView {
|
||||
return AssetView.{}
|
||||
}
|
||||
preview := path[6:14] == "preview/"
|
||||
key := ifx preview then MediaPreviewKey(hash) else MediaRecordKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
content := MediaContentOf(hash, preview)
|
||||
file := MediaPath(hash, preview)
|
||||
defer {
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
PackageFree(file)
|
||||
}
|
||||
media := DiaryMediaParse(record)
|
||||
PackageFree(media_asset_bytes)
|
||||
media_asset_bytes = PackageRead(file, DIARY_FILE_LIMIT)
|
||||
format := DiaryImageFormat(media_asset_bytes)
|
||||
@@ -947,7 +1168,7 @@ MediaAssetView :: (path: string) -> AssetView {
|
||||
while at > 0 && path[at] != cast(u8)46 {
|
||||
at -= 1
|
||||
}
|
||||
if !DiaryMediaMatches(media, media_asset_bytes) || format != path[at + 1:] {
|
||||
if !EntityContentMatches(content, media_asset_bytes) || format != path[at + 1:] {
|
||||
PackageFree(media_asset_bytes)
|
||||
media_asset_bytes = ""
|
||||
return AssetView.{}
|
||||
@@ -957,39 +1178,47 @@ MediaAssetView :: (path: string) -> AssetView {
|
||||
|
||||
// Changes.
|
||||
|
||||
// Moves a photo to Trash or back. Trash keeps the photo and its copies.
|
||||
MediaSetTrashed :: (hash: string, trashed: bool) -> bool {
|
||||
// Sets one field of the photo's record, keeping all others: its entity
|
||||
// record, or a released version's while it has none.
|
||||
MediaSetField :: (hash: string, field: string, entity_value: string, legacy_value: string) -> bool {
|
||||
if !MediaRead(hash).valid {
|
||||
return false
|
||||
}
|
||||
key := MediaRecordKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
changed := MediaRecordWith(record, "trashed", ifx trashed then "1" else "0")
|
||||
written := changed.count > 0 && MediaRecordWrite(key, changed)
|
||||
PackageFree(key)
|
||||
entity_key := EntityPhotoKey(hash)
|
||||
entity_record := MediaRecordRead(entity_key)
|
||||
legacy_key := MediaRecordKey(hash)
|
||||
defer {
|
||||
PackageFree(entity_key)
|
||||
PackageFree(entity_record)
|
||||
PackageFree(legacy_key)
|
||||
}
|
||||
if entity_record.count > 0 {
|
||||
changed := MediaRecordWith(entity_record, field, entity_value)
|
||||
written := changed.count > 0 && MediaRecordWrite(entity_key, changed)
|
||||
PackageFree(changed)
|
||||
return written
|
||||
}
|
||||
record := MediaRecordRead(legacy_key)
|
||||
changed := MediaRecordWith(record, field, legacy_value)
|
||||
written := changed.count > 0 && MediaRecordWrite(legacy_key, changed)
|
||||
PackageFree(record)
|
||||
PackageFree(changed)
|
||||
return written
|
||||
}
|
||||
|
||||
// Moves a photo to Trash or back. Trash keeps the photo and its copies.
|
||||
MediaSetTrashed :: (hash: string, trashed: bool) -> bool {
|
||||
return MediaSetField(hash, "trashed", ifx trashed then "true" else "false", ifx trashed then "1" else "0")
|
||||
}
|
||||
|
||||
// Renames a photo: one line of at most MEDIA_NAME_MAX bytes.
|
||||
MediaSetName :: (hash: string, name: string) -> bool {
|
||||
if !MediaRead(hash).valid {
|
||||
return false
|
||||
}
|
||||
trimmed := MediaNameCut(name)
|
||||
out: Vec(u8)
|
||||
MediaJson(*out, trimmed)
|
||||
quoted := BuilderFinish(out)
|
||||
key := MediaRecordKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
changed := MediaRecordWith(record, "name", quoted)
|
||||
written := changed.count > 0 && MediaRecordWrite(key, changed)
|
||||
PackageFree(quoted)
|
||||
PackageFree(key)
|
||||
PackageFree(record)
|
||||
PackageFree(changed)
|
||||
return written
|
||||
defer { PackageFree(quoted) }
|
||||
return MediaSetField(hash, "name", quoted, quoted)
|
||||
}
|
||||
|
||||
MediaStoreClose :: () {
|
||||
|
||||
@@ -36,7 +36,7 @@ AchievementSourceTriggers :: () -> bool {
|
||||
// achievement records are sources.
|
||||
if table == "settings" {
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "WHEN %.key GLOB 'cell.diary.file.*' OR %.key GLOB 'cell.media.*' OR %.key GLOB 'cell.achievement.*'", row, row, row)
|
||||
BuilderPrint(*out, "WHEN %.key GLOB 'cell.diary.file.*' OR %.key GLOB 'cell.media.*' OR %.key GLOB 'entity.photos.*' OR %.key GLOB 'cell.achievement.*'", row, row, row, row)
|
||||
when = BuilderFinish(out)
|
||||
}
|
||||
defer { if when.count > 0 { PackageFree(when) } }
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
// Entity records in Daochi's encrypted record profile (daochi-record-v1,
|
||||
// Daochi docs/encrypted-record-profile-v1.md and docs/entity-data.md), so
|
||||
// every app of the account reads what this one writes. A record is sealed
|
||||
// with XChaCha20-Poly1305, a fresh 24-byte nonce and the record key of its
|
||||
// kind; the associated data names the account, the entity app, the
|
||||
// collection, the record and its schema:
|
||||
//
|
||||
// {"account_id":…,"app_id":"entity","collection":…,"id":…,"schema":…}
|
||||
//
|
||||
// The envelope is sorted-key JSON whose binary fields are base64url without
|
||||
// padding, as DaochiClient's SealRecord writes it:
|
||||
//
|
||||
// {"aad":{…},"alg":"xchacha20poly1305","ciphertext":…,"key_id":"entity-v1",
|
||||
// "nonce":…,"profile":"daochi-record-v1"}
|
||||
//
|
||||
// In a sync request the record's "ciphertext" is the envelope, base64url, and
|
||||
// its "nonce" the nonce. Monocypher's AEAD is the same XChaCha20-Poly1305 as
|
||||
// libsodium's, which other apps use (tests/entity_records_test.py).
|
||||
#import "byte_text_linux"
|
||||
#import "vec"
|
||||
#import "keys"
|
||||
#import "daochi_client/entity"
|
||||
Scan :: #import "json_scan"
|
||||
|
||||
entity_record_c :: #system_library "c";
|
||||
EntityLock :: (cipher: *u8, mac: *u8, key: *u8, nonce: *u8, ad: *u8, ad_size: usize,
|
||||
plain: *u8, size: usize) #foreign entity_record_c "crypto_aead_lock";
|
||||
EntityUnlock :: (plain: *u8, mac: *u8, key: *u8, nonce: *u8, ad: *u8, ad_size: usize,
|
||||
cipher: *u8, size: usize) -> s32 #foreign entity_record_c "crypto_aead_unlock";
|
||||
EntityAllocate :: (size: usize) -> *void #foreign entity_record_c "malloc";
|
||||
EntityRelease :: (pointer: *void) #foreign entity_record_c "free";
|
||||
|
||||
ENTITY_RECORD_APP_ID :: "entity"
|
||||
ENTITY_RECORD_PROFILE :: "daochi-record-v1"
|
||||
ENTITY_RECORD_ALGORITHM :: "xchacha20poly1305"
|
||||
ENTITY_RECORD_NONCE_BYTES :: 24
|
||||
ENTITY_RECORD_TAG_BYTES :: 16
|
||||
// A record's plain text is one JSON document; the profile allows 8 MiB.
|
||||
ENTITY_RECORD_PLAIN_MAX :: 8388608
|
||||
|
||||
// Unescaped printable ASCII without quotes or backslashes, so the associated
|
||||
// data is the same canonical JSON in every implementation.
|
||||
EntityRecordPlain :: (value: string) -> bool {
|
||||
if value.count < 1 || value.count > 256 {
|
||||
return false
|
||||
}
|
||||
for byte: value {
|
||||
if byte < cast(u8)32 || byte > cast(u8)126 || byte == cast(u8)34 || byte == cast(u8)92 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// What a record's associated data names.
|
||||
EntityRecordMetadata :: struct {
|
||||
account_id: string
|
||||
collection: string
|
||||
id: string
|
||||
schema: string
|
||||
}
|
||||
|
||||
EntityRecordMetadataValid :: (metadata: EntityRecordMetadata) -> bool {
|
||||
return metadata.account_id.count == 64 && EntityRecordPlain(metadata.account_id) &&
|
||||
EntityRecordPlain(metadata.collection) && EntityRecordPlain(metadata.id) &&
|
||||
EntityRecordPlain(metadata.schema)
|
||||
}
|
||||
|
||||
// Each metadata value is at most 256 bytes, so the associated data fits.
|
||||
ENTITY_RECORD_AAD_MAX :: 1200
|
||||
|
||||
EntityRecordAppend :: (output: []u8, length: s64, text: string) -> s64 {
|
||||
if length < 0 || length + text.count > output.count {
|
||||
return -1
|
||||
}
|
||||
at := length
|
||||
for byte: text {
|
||||
output[at] = byte
|
||||
at += 1
|
||||
}
|
||||
return at
|
||||
}
|
||||
|
||||
// The associated data in output; its length, or -1 when it does not fit.
|
||||
EntityRecordAAD :: (metadata: EntityRecordMetadata, output: []u8) -> s64 {
|
||||
length := EntityRecordAppend(output, 0, "{\"account_id\":\"")
|
||||
length = EntityRecordAppend(output, length, metadata.account_id)
|
||||
length = EntityRecordAppend(output, length, "\",\"app_id\":\"")
|
||||
length = EntityRecordAppend(output, length, ENTITY_RECORD_APP_ID)
|
||||
length = EntityRecordAppend(output, length, "\",\"collection\":\"")
|
||||
length = EntityRecordAppend(output, length, metadata.collection)
|
||||
length = EntityRecordAppend(output, length, "\",\"id\":\"")
|
||||
length = EntityRecordAppend(output, length, metadata.id)
|
||||
length = EntityRecordAppend(output, length, "\",\"schema\":\"")
|
||||
length = EntityRecordAppend(output, length, metadata.schema)
|
||||
return EntityRecordAppend(output, length, "\"}")
|
||||
}
|
||||
|
||||
ENTITY_BASE64_ALPHABET :: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
|
||||
|
||||
// Base64url without padding.
|
||||
EntityBase64Append :: (out: *Vec(u8), bytes: []u8) {
|
||||
alphabet := ENTITY_BASE64_ALPHABET
|
||||
at: s64 = 0
|
||||
while at + 3 <= bytes.count {
|
||||
value := (cast(u32)bytes[at] << 16) | (cast(u32)bytes[at + 1] << 8) | cast(u32)bytes[at + 2]
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 18) & 63)])
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 12) & 63)])
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 6) & 63)])
|
||||
unused VecPush(out.*, alphabet[cast(s64)(value & 63)])
|
||||
at += 3
|
||||
}
|
||||
left := bytes.count - at
|
||||
if left == 1 {
|
||||
value := cast(u32)bytes[at] << 16
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 18) & 63)])
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 12) & 63)])
|
||||
} else if left == 2 {
|
||||
value := (cast(u32)bytes[at] << 16) | (cast(u32)bytes[at + 1] << 8)
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 18) & 63)])
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 12) & 63)])
|
||||
unused VecPush(out.*, alphabet[cast(s64)((value >> 6) & 63)])
|
||||
}
|
||||
}
|
||||
|
||||
EntityBase64Digit :: (byte: u8) -> s32 {
|
||||
if byte >= #char "A" && byte <= #char "Z" {
|
||||
return cast(s32)(byte - #char "A")
|
||||
}
|
||||
if byte >= #char "a" && byte <= #char "z" {
|
||||
return cast(s32)(byte - #char "a") + 26
|
||||
}
|
||||
if byte >= #char "0" && byte <= #char "9" {
|
||||
return cast(s32)(byte - #char "0") + 52
|
||||
}
|
||||
if byte == #char "-" {
|
||||
return 62
|
||||
}
|
||||
if byte == #char "_" {
|
||||
return 63
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// The decoded length of base64url text without padding, or -1 for a length
|
||||
// no encoding has.
|
||||
EntityBase64Size :: (count: s64) -> s64 {
|
||||
if count % 4 == 1 {
|
||||
return -1
|
||||
}
|
||||
return count / 4 * 3 + ifx count % 4 == 0 then cast(s64)0 else count % 4 - 1
|
||||
}
|
||||
|
||||
// Decodes text into output; the length, or -1 when text is not canonical
|
||||
// base64url without padding or output is too small.
|
||||
EntityBase64Decode :: (text: string, output: []u8) -> s64 {
|
||||
size := EntityBase64Size(text.count)
|
||||
if size < 0 || size > output.count {
|
||||
return -1
|
||||
}
|
||||
value: u32 = 0
|
||||
bits: s32 = 0
|
||||
length: s64 = 0
|
||||
for byte: text {
|
||||
digit := EntityBase64Digit(byte)
|
||||
if digit < 0 {
|
||||
return -1
|
||||
}
|
||||
value = (value << 6) | cast(u32)digit
|
||||
bits += 6
|
||||
if bits >= 8 {
|
||||
bits -= 8
|
||||
output[length] = cast(u8)((value >> cast(u32)bits) & 255)
|
||||
length += 1
|
||||
}
|
||||
}
|
||||
// Leftover bits must be zero, so each record has one encoding.
|
||||
if bits > 0 && (value & ((cast(u32)1 << cast(u32)bits) - 1)) != 0 {
|
||||
return -1
|
||||
}
|
||||
return length
|
||||
}
|
||||
|
||||
// Seals plain under key as the profile's envelope, with a fresh random
|
||||
// nonce. `ciphertext` receives the envelope and `nonce` the nonce, both
|
||||
// base64url as a sync request carries them.
|
||||
EntitySealRecord :: (key: *u8, metadata: EntityRecordMetadata, plain: []u8,
|
||||
ciphertext: *Vec(u8), nonce: *Vec(u8)) -> bool {
|
||||
random: [ENTITY_RECORD_NONCE_BYTES]u8
|
||||
if SecureRandom(*random[0], ENTITY_RECORD_NONCE_BYTES) == 0 {
|
||||
return false
|
||||
}
|
||||
return EntitySealRecordWith(key, metadata, plain, random[:], ciphertext, nonce)
|
||||
}
|
||||
|
||||
// EntitySealRecord with a given nonce, which must never repeat for a key:
|
||||
// known-answer tests compare its envelope with other implementations'.
|
||||
EntitySealRecordWith :: (key: *u8, metadata: EntityRecordMetadata, plain: []u8, random: []u8,
|
||||
ciphertext: *Vec(u8), nonce: *Vec(u8)) -> bool {
|
||||
if key == null || !EntityRecordMetadataValid(metadata) || plain.count < 1 ||
|
||||
plain.count > ENTITY_RECORD_PLAIN_MAX || random.count != ENTITY_RECORD_NONCE_BYTES {
|
||||
return false
|
||||
}
|
||||
aad: [ENTITY_RECORD_AAD_MAX]u8
|
||||
aad_count := EntityRecordAAD(metadata, aad[:])
|
||||
if aad_count < 0 {
|
||||
return false
|
||||
}
|
||||
sealed_count := plain.count + ENTITY_RECORD_TAG_BYTES
|
||||
sealed := cast(*u8)EntityAllocate(cast(usize)sealed_count)
|
||||
if sealed == null {
|
||||
return false
|
||||
}
|
||||
defer {
|
||||
SecureWipe(sealed, sealed_count)
|
||||
EntityRelease(cast(*void)sealed)
|
||||
}
|
||||
EntityLock(sealed, *sealed[plain.count], key, *random[0], *aad[0], cast(usize)aad_count,
|
||||
*plain[0], cast(usize)plain.count)
|
||||
envelope: Vec(u8)
|
||||
defer { VecFree(envelope) }
|
||||
BuilderPrint(*envelope, "{\"aad\":%,\"alg\":\"%\",\"ciphertext\":\"",
|
||||
TextFromBytes(aad[:aad_count]), ENTITY_RECORD_ALGORITHM)
|
||||
EntityBase64Append(*envelope, BytesFromPointer(sealed, cast(u64)sealed_count))
|
||||
BuilderPrint(*envelope, "\",\"key_id\":\"%\",\"nonce\":\"", ENTITY_RECORD_KEY_ID)
|
||||
EntityBase64Append(*envelope, random)
|
||||
BuilderPrint(*envelope, "\",\"profile\":\"%\"}", ENTITY_RECORD_PROFILE)
|
||||
EntityBase64Append(ciphertext, VecSlice(envelope, 0, envelope.count))
|
||||
EntityBase64Append(nonce, random)
|
||||
return true
|
||||
}
|
||||
|
||||
// Whether the string at `at` in text is exactly `expected`.
|
||||
EntityRecordField :: (text: string, at: s32, expected: string) -> bool {
|
||||
if at < 0 {
|
||||
return false
|
||||
}
|
||||
return Scan.SpanEqualsASCII(text, Scan.ReadString(text, at), expected)
|
||||
}
|
||||
|
||||
// The plain text of a record whose envelope names this record, or empty: a
|
||||
// NUL-terminated copy to free with EntityRelease, through `plain`. The
|
||||
// associated data is authenticated as the writer serialized it, and each of
|
||||
// its fields must name this account, app, collection, record and schema.
|
||||
EntityOpenRecord :: (key: *u8, metadata: EntityRecordMetadata, key_id: string,
|
||||
nonce_text: string, ciphertext_text: string, plain: **u8) -> s64 {
|
||||
plain.* = null
|
||||
if key == null || !EntityRecordMetadataValid(metadata) || key_id != ENTITY_RECORD_KEY_ID {
|
||||
return -1
|
||||
}
|
||||
envelope_size := EntityBase64Size(ciphertext_text.count)
|
||||
if envelope_size < 2 || envelope_size > ENTITY_RECORD_PLAIN_MAX * 2 {
|
||||
return -1
|
||||
}
|
||||
envelope_pointer := cast(*u8)EntityAllocate(cast(usize)envelope_size)
|
||||
if envelope_pointer == null {
|
||||
return -1
|
||||
}
|
||||
defer { EntityRelease(cast(*void)envelope_pointer) }
|
||||
envelope_bytes := BytesFromPointer(envelope_pointer, cast(u64)envelope_size)
|
||||
if EntityBase64Decode(ciphertext_text, envelope_bytes) != envelope_size {
|
||||
return -1
|
||||
}
|
||||
envelope := TextFromBytes(envelope_bytes)
|
||||
start := Scan.Space(envelope, 0)
|
||||
if start < 0 || Scan.Space(envelope, Scan.ValueEnd(envelope, start, 0)) != cast(s32)envelope.count {
|
||||
return -1
|
||||
}
|
||||
aad_at := Scan.FieldAt(envelope, start, "aad")
|
||||
aad_end := ifx aad_at < 0 then cast(s32)-1 else Scan.ValueEnd(envelope, aad_at, 0)
|
||||
if aad_at < 0 || aad_end <= aad_at || envelope[aad_at] != cast(u8)123 ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, start, "profile"), ENTITY_RECORD_PROFILE) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, start, "alg"), ENTITY_RECORD_ALGORITHM) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, start, "key_id"), ENTITY_RECORD_KEY_ID) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, start, "nonce"), nonce_text) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, aad_at, "account_id"), metadata.account_id) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, aad_at, "app_id"), ENTITY_RECORD_APP_ID) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, aad_at, "collection"), metadata.collection) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, aad_at, "id"), metadata.id) ||
|
||||
!EntityRecordField(envelope, Scan.FieldAt(envelope, aad_at, "schema"), metadata.schema) {
|
||||
return -1
|
||||
}
|
||||
nonce: [ENTITY_RECORD_NONCE_BYTES]u8
|
||||
if EntityBase64Decode(nonce_text, nonce[:]) != ENTITY_RECORD_NONCE_BYTES {
|
||||
return -1
|
||||
}
|
||||
sealed_at := Scan.FieldAt(envelope, start, "ciphertext")
|
||||
sealed_span := Scan.ReadString(envelope, sealed_at)
|
||||
if sealed_at < 0 || !sealed_span.valid {
|
||||
return -1
|
||||
}
|
||||
sealed_text := envelope[sealed_span.start:sealed_span.end]
|
||||
sealed_size := EntityBase64Size(sealed_text.count)
|
||||
if sealed_size <= ENTITY_RECORD_TAG_BYTES || sealed_size > ENTITY_RECORD_PLAIN_MAX + ENTITY_RECORD_TAG_BYTES {
|
||||
return -1
|
||||
}
|
||||
sealed := cast(*u8)EntityAllocate(cast(usize)sealed_size)
|
||||
if sealed == null {
|
||||
return -1
|
||||
}
|
||||
defer { EntityRelease(cast(*void)sealed) }
|
||||
if EntityBase64Decode(sealed_text, BytesFromPointer(sealed, cast(u64)sealed_size)) != sealed_size {
|
||||
return -1
|
||||
}
|
||||
length := sealed_size - ENTITY_RECORD_TAG_BYTES
|
||||
output := cast(*u8)EntityAllocate(cast(usize)(length + 1))
|
||||
if output == null {
|
||||
return -1
|
||||
}
|
||||
aad := envelope[aad_at:aad_end]
|
||||
aad_bytes := cast(*TextDescriptor)(*aad)
|
||||
if EntityUnlock(output, *sealed[length], key, *nonce[0], aad_bytes.data, cast(usize)aad.count,
|
||||
sealed, cast(usize)length) != 0 {
|
||||
SecureWipe(output, length + 1)
|
||||
EntityRelease(cast(*void)output)
|
||||
return -1
|
||||
}
|
||||
output[length] = cast(u8)0
|
||||
plain.* = output
|
||||
return length
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// Names of the account's entity data (Daochi docs/entity-data.md): what the
|
||||
// account owns, kept once for the account and shared by every app it uses,
|
||||
// whichever app added it. This version keeps one kind, photos. Each photo is
|
||||
// one record, entity.photos.<sha256> on this device, that syncs as record
|
||||
// <sha256> of private.entity.v1.photos in the account's own signed sync,
|
||||
// sealed with the account's entity key for photos (entity_record_crypto.zi).
|
||||
// Its bytes travel as sealed chunks (cells/diary_blobs.zi). Everything is
|
||||
// private: nothing here is shared without a separate, explicit step.
|
||||
#import, file "media_records.zi";
|
||||
|
||||
EntityPhotosCollection :: "private.entity.v1.photos"
|
||||
ENTITY_PHOTOS_KIND :: "photos"
|
||||
ENTITY_PHOTO_SCHEMA :: "entity.photo.v1"
|
||||
ENTITY_PHOTO_PREFIX :: "entity.photos."
|
||||
// The record of a photo on this device: the prefix and 64 hex digits.
|
||||
ENTITY_PHOTO_KEY_BYTES :: 78
|
||||
|
||||
// entity.photos.<sha256>, the key of one photo's record on this device.
|
||||
EntityPhotoKeyAccepted :: (key: string) -> bool {
|
||||
return EntityPhotoKeyHash(key).count == 64
|
||||
}
|
||||
|
||||
// The photo's hash in entity.photos.<sha256>, or empty.
|
||||
EntityPhotoKeyHash :: (key: string) -> string {
|
||||
prefix := ENTITY_PHOTO_PREFIX
|
||||
if key.count != ENTITY_PHOTO_KEY_BYTES || key[:prefix.count] != prefix ||
|
||||
!MediaHashValid(key[prefix.count:]) {
|
||||
return ""
|
||||
}
|
||||
return key[prefix.count:]
|
||||
}
|
||||
|
||||
// The collection a local entity record syncs in, or empty.
|
||||
EntityRecordCollection :: (key: string) -> string {
|
||||
if EntityPhotoKeyAccepted(key) {
|
||||
return EntityPhotosCollection
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Entity collections this version reads; records of other kinds, such as
|
||||
// another app's levels, arrive in the same replies and are left alone.
|
||||
EntityCollectionKnown :: (collection: string) -> bool {
|
||||
return collection == EntityPhotosCollection
|
||||
}
|
||||
|
||||
EntityCollectionKind :: (collection: string) -> string {
|
||||
if collection == EntityPhotosCollection {
|
||||
return ENTITY_PHOTOS_KIND
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
EntityCollectionSchema :: (collection: string) -> string {
|
||||
if collection == EntityPhotosCollection {
|
||||
return ENTITY_PHOTO_SCHEMA
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
// Names of the account's media library records. Each photo is one record,
|
||||
// cell.media.<sha256>, and its gallery preview another,
|
||||
// Names of the media library records released versions keep. Each photo is
|
||||
// one record, cell.media.<sha256>, and its gallery preview another,
|
||||
// cell.media.preview.<sha256>, both keyed by the SHA-256 of the photo's
|
||||
// bytes. They sync in their own collection, private.inbe.v1.media: released
|
||||
// versions reject unknown keys in the older collections but skip unknown
|
||||
// collections, so none of this goes there.
|
||||
// collections, so none of this goes there. This version keeps photos in the
|
||||
// account's entity data (entity_records.zi) and only reads and points these
|
||||
// records, which released versions read through 2027-10-24.
|
||||
|
||||
MediaCollection :: "private.inbe.v1.media"
|
||||
MEDIA_RECORD_PREFIX :: "cell.media."
|
||||
|
||||
@@ -253,6 +253,12 @@ migrate_schema :: () -> s32 {
|
||||
if !SchemaExec(SchemaDiaryBlobs) {
|
||||
return SchemaUpgradeFailed()
|
||||
}
|
||||
if !SchemaExec(SchemaOldCopiesDeleted) {
|
||||
return SchemaUpgradeFailed()
|
||||
}
|
||||
if !SchemaExec(SchemaVerifiedContents) {
|
||||
return SchemaUpgradeFailed()
|
||||
}
|
||||
if SchemaHasColumn("habit_days", "answers") && !SchemaExec(SchemaDayAnswersToEntries) {
|
||||
return SchemaUpgradeFailed()
|
||||
}
|
||||
|
||||
@@ -333,6 +333,26 @@ CREATE TABLE IF NOT EXISTS diary_blobs( node TEXT NOT NULL,
|
||||
PRIMARY KEY(node,blob))
|
||||
SQL
|
||||
|
||||
// Old copies of photos that moved to the account's entity data, by the
|
||||
// node that deleted them and their address, so each is deleted once per
|
||||
// node (cells/diary_blobs.zi). Only this device keeps it; a lost row means
|
||||
// one more delete, which the node answers the same.
|
||||
SchemaOldCopiesDeleted :: #string SQL
|
||||
CREATE TABLE IF NOT EXISTS old_copies_deleted( node TEXT NOT NULL,
|
||||
blob TEXT NOT NULL,
|
||||
PRIMARY KEY(node,blob))
|
||||
SQL
|
||||
|
||||
// Photo contents of the account's entity data, by their hash, that this
|
||||
// device downloaded back from a node and found whole, so an old copy of the
|
||||
// photo may go (cells/diary_blobs.zi). Only this device keeps it; a lost
|
||||
// row means one more check.
|
||||
SchemaVerifiedContents :: #string SQL
|
||||
CREATE TABLE IF NOT EXISTS verified_contents( node TEXT NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
PRIMARY KEY(node,hash))
|
||||
SQL
|
||||
|
||||
// A habit's entries: each a moment of a day, or a span from its start to
|
||||
// its end (0 while it runs), with its answers to the habit's questions as
|
||||
// a JSON array. An entry belongs to the day it started.
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#import, file "cell_records.zi";
|
||||
#import, file "app_records.zi";
|
||||
#import, file "media_records.zi";
|
||||
#import, file "entity_records.zi";
|
||||
#import, file "habit_settings.zi";
|
||||
#import, file "db.zi";
|
||||
#import, file "storage_core.zi";
|
||||
@@ -351,6 +352,9 @@ storage_set_setting_text :: (key: string, value: string) {
|
||||
if MediaRecordKeyAccepted(key) {
|
||||
unused storage_enqueue_sync_entity("media_record", key, 0)
|
||||
}
|
||||
if EntityPhotoKeyAccepted(key) {
|
||||
unused storage_enqueue_sync_entity("entity_record", key, 0)
|
||||
}
|
||||
if storage_state_handle().settings_write_depth <= 0 {
|
||||
storage_schedule_persist()
|
||||
}
|
||||
|
||||
+76
-13
@@ -3,6 +3,7 @@
|
||||
// after checking that it is a record this version can read.
|
||||
#import, file "../app/text_buffers.zi";
|
||||
#import "byte_text_linux"
|
||||
#import "text_buffer"
|
||||
Scan :: #import "json_scan"
|
||||
#import, file "../cells/catalog.zi";
|
||||
#import, file "state.zi";
|
||||
@@ -14,6 +15,8 @@ Scan :: #import "json_scan"
|
||||
#import, file "app_records.zi";
|
||||
#import, file "achievement_records.zi";
|
||||
#import, file "media_records.zi";
|
||||
#import, file "entity_records.zi";
|
||||
#import, file "entity_record_crypto.zi";
|
||||
#import, file "storage_layout.zi";
|
||||
#import, file "db.zi";
|
||||
#import, file "storage_habit_sync.zi";
|
||||
@@ -291,7 +294,52 @@ storage_apply_decrypted_record :: (collection: string, record_id: string, plaint
|
||||
return ok
|
||||
}
|
||||
|
||||
storage_apply_encrypted_records_query: string = "SELECT json_extract(value,'$.collection'),json_extract(value,'$.id'),json_extract(value,'$.key_id'),json_extract(value,'$.nonce'),json_extract(value,'$.ciphertext'),COALESCE(json_extract(value,'$.content_hash'),'')FROM json_each(?1,?2)";
|
||||
storage_apply_encrypted_records_query: string = "SELECT json_extract(value,'$.collection'),json_extract(value,'$.id'),json_extract(value,'$.key_id'),json_extract(value,'$.nonce'),json_extract(value,'$.ciphertext'),COALESCE(json_extract(value,'$.content_hash'),''),COALESCE(json_extract(value,'$.updated_at'),'')FROM json_each(?1,?2)";
|
||||
|
||||
// A photo of the account's entity data, as another app or device wrote it:
|
||||
// one JSON object naming the photo it is the record of.
|
||||
storage_entity_photo_valid :: (record_id: string, plaintext: string) -> bool {
|
||||
start := Scan.Space(plaintext, 0)
|
||||
if start < 0 || start >= cast(s32)plaintext.count || plaintext[start] != cast(u8)123 ||
|
||||
Scan.Space(plaintext, Scan.ValueEnd(plaintext, start, 0)) != cast(s32)plaintext.count {
|
||||
return false
|
||||
}
|
||||
hash: [65]u8
|
||||
size := Scan.ReadNumber(plaintext, Scan.FieldAt(plaintext, start, "size"))
|
||||
return Scan.ReadStringText(plaintext, Scan.FieldAt(plaintext, start, "hash"), hash[:]) == 64 &&
|
||||
TextFromBytes(hash[:64]) == record_id && MediaHashValid(record_id) && size.valid && size.value >= 1.0
|
||||
}
|
||||
|
||||
// Stores an entity record that arrived, in the order the node keeps them:
|
||||
// it replaces this device's copy, keeping fields only this device has,
|
||||
// unless this device changed the record and has not sent the change yet.
|
||||
// That change goes out merged over the record that arrived.
|
||||
storage_apply_entity_record :: (collection: string, record_id: string, plaintext: string,
|
||||
updated_at: string) -> s32 {
|
||||
if collection != EntityPhotosCollection || !storage_entity_photo_valid(record_id, plaintext) {
|
||||
LogStorageText(LOG_WARNING, "SYNC: entity record skipped: ", collection)
|
||||
return 1
|
||||
}
|
||||
key: [ENTITY_PHOTO_KEY_BYTES + 1]u8
|
||||
unused AppCopyText(ENTITY_PHOTO_PREFIX, key[:])
|
||||
unused AppAppendText(record_id, key[:])
|
||||
statement: *void = null
|
||||
if SqlitePrepareText(storage_db_handle(), SyncEntityRecordSQL, -1, *statement, null) != SQLITE_OK {
|
||||
return 0
|
||||
}
|
||||
defer { SqliteFinalize(statement) }
|
||||
bind_text(statement, 1, AppTextFromCString(storage_user_id_buffer(), 64))
|
||||
bind_text(statement, 2, TextUntilNul(key[:]))
|
||||
bind_text(statement, 3, plaintext)
|
||||
bind_text(statement, 4, updated_at)
|
||||
if SqliteStep(statement) != SQLITE_DONE {
|
||||
return 0
|
||||
}
|
||||
if sqlite3_changes(storage_db_handle()) > 0 {
|
||||
storage_media_changes += 1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
storage_apply_encrypted_records :: (response_json: string) -> s32 {
|
||||
habit_batch_storage: StorageJsonBuilder = StorageJsonBuilder.{}
|
||||
@@ -312,7 +360,7 @@ storage_apply_encrypted_records :: (response_json: string) -> s32 {
|
||||
if count <= 0 {
|
||||
return 1
|
||||
}
|
||||
fields = cast(**u8)calloc(cast(usize)count * 6,
|
||||
fields = cast(**u8)calloc(cast(usize)count * 7,
|
||||
cast(usize)size_of(type_of(<<fields)))
|
||||
if fields == null {
|
||||
return 0
|
||||
@@ -326,14 +374,14 @@ storage_apply_encrypted_records :: (response_json: string) -> s32 {
|
||||
while loaded < count && SqliteStep(statement) == SQLITE_ROW {
|
||||
{
|
||||
column: s32 = 0
|
||||
while column < 6 {
|
||||
while column < 7 {
|
||||
value: *u8 = SqliteColumnText(statement, column)
|
||||
if value == null {
|
||||
fields[loaded * 6 + column] = cast(*u8)calloc(1, 1)
|
||||
fields[loaded * 7 + column] = cast(*u8)calloc(1, 1)
|
||||
} else {
|
||||
fields[loaded * 6 + column] = storage_duplicate_cstring(value)
|
||||
fields[loaded * 7 + column] = storage_duplicate_cstring(value)
|
||||
}
|
||||
if fields[loaded * 6 + column] == null {
|
||||
if fields[loaded * 7 + column] == null {
|
||||
ok = 0
|
||||
break
|
||||
}
|
||||
@@ -352,16 +400,31 @@ storage_apply_encrypted_records :: (response_json: string) -> s32 {
|
||||
{
|
||||
index: s32 = 0
|
||||
while ok != 0 && index < loaded {
|
||||
collection: string = AppTextFromCString(fields[index * 6], 2147483647)
|
||||
record_id: string = AppTextFromCString(fields[index * 6 + 1], 2147483647)
|
||||
key_id: string = AppTextFromCString(fields[index * 6 + 2], 2147483647)
|
||||
nonce: string = AppTextFromCString(fields[index * 6 + 3], 2147483647)
|
||||
ciphertext: string = AppTextFromCString(fields[index * 6 + 4], 2147483647)
|
||||
content_hash: string = AppTextFromCString(fields[index * 6 + 5], 2147483647)
|
||||
collection: string = AppTextFromCString(fields[index * 7], 2147483647)
|
||||
record_id: string = AppTextFromCString(fields[index * 7 + 1], 2147483647)
|
||||
key_id: string = AppTextFromCString(fields[index * 7 + 2], 2147483647)
|
||||
nonce: string = AppTextFromCString(fields[index * 7 + 3], 2147483647)
|
||||
ciphertext: string = AppTextFromCString(fields[index * 7 + 4], 2147483647)
|
||||
content_hash: string = AppTextFromCString(fields[index * 7 + 5], 2147483647)
|
||||
updated_at: string = AppTextFromCString(fields[index * 7 + 6], 2147483647)
|
||||
plaintext: *u8 = null
|
||||
if collection.count == 0 || storage_decrypted_array_name(collection).count == 0 {
|
||||
index += 1; continue
|
||||
}
|
||||
if EntityCollectionKnown(collection) {
|
||||
// An entity record another app wrote and this one cannot
|
||||
// open changes nothing here and doesn't stop the sync.
|
||||
if storage_open_entity_record(collection, record_id, key_id, nonce, ciphertext, *plaintext) == 0 {
|
||||
LogStorageText(LOG_WARNING, "SYNC: entity record could not be opened: ", collection)
|
||||
} else {
|
||||
entity_plain := AppTextFromCString(plaintext, ENTITY_RECORD_PLAIN_MAX + 1)
|
||||
storage_sync_record_copy_store(collection, record_id, entity_plain)
|
||||
ok = storage_apply_entity_record(collection, record_id, entity_plain, updated_at)
|
||||
free(cast(*void)plaintext)
|
||||
}
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
ok = ifx (record_id.count > 0 && key_id.count > 0 && nonce.count > 0 && ciphertext.count > 0 && storage_decrypt_record(collection, record_id, key_id, nonce,
|
||||
ciphertext, content_hash, *plaintext) != 0) then (1) else (0)
|
||||
if ok != 0 {
|
||||
@@ -404,7 +467,7 @@ storage_apply_encrypted_records :: (response_json: string) -> s32 {
|
||||
}
|
||||
{
|
||||
index: s32 = 0
|
||||
while index < count * 6 {
|
||||
while index < count * 7 {
|
||||
free(cast(*void)fields[index])
|
||||
index += 1
|
||||
}
|
||||
|
||||
@@ -7,9 +7,11 @@
|
||||
#import, file "achievement_records.zi";
|
||||
#import, file "app_records.zi";
|
||||
#import, file "media_records.zi";
|
||||
#import, file "entity_records.zi";
|
||||
#import, file "habit_settings.zi";
|
||||
#import, file "storage_layout.zi";
|
||||
#import, file "storage_core.zi";
|
||||
#import "daochi_client/entity"
|
||||
|
||||
// The collection of a node app's record key, such as
|
||||
// private.inbe.v1.app.chess, held until the next call.
|
||||
@@ -57,6 +59,9 @@ storage_encrypted_collection_for_entity :: (entity_type: string, entity_id: stri
|
||||
if entity_type == "media_record" {
|
||||
return ifx MediaRecordKeyAccepted(entity_id) then MediaCollection else ""
|
||||
}
|
||||
if entity_type == "entity_record" {
|
||||
return EntityRecordCollection(entity_id)
|
||||
}
|
||||
if entity_type.count == 0 {
|
||||
return ""
|
||||
}
|
||||
@@ -97,7 +102,11 @@ storage_encrypted_record_id :: (entity_type: string, entity_id: string, local_da
|
||||
}
|
||||
out[0] = cast(u8)0
|
||||
written = 0
|
||||
if storage_compare_text(entity_type, "habit_day") == 0 {
|
||||
if entity_type == "entity_record" {
|
||||
// An entity record is named by its content's hash alone, as every
|
||||
// app of the account names it.
|
||||
AppCopyText(EntityPhotoKeyHash(entity_id), BytesFromPointer(out, cast(u64)out_size))
|
||||
} else if storage_compare_text(entity_type, "habit_day") == 0 {
|
||||
AppCopyText(entity_id, BytesFromPointer(out, cast(u64)out_size))
|
||||
date_text: [16] u8
|
||||
AppFormatS32(local_date, date_text[:])
|
||||
@@ -121,6 +130,9 @@ storage_encrypted_collection_key_id :: (collection: string) -> string {
|
||||
if collection == LumiPrivateCollection {
|
||||
return LumiPrivateKeyID
|
||||
}
|
||||
if EntityCollectionKnown(collection) {
|
||||
return ENTITY_RECORD_KEY_ID
|
||||
}
|
||||
return STORAGE_SYNC_RECORD_KEY_ID
|
||||
}
|
||||
|
||||
@@ -144,6 +156,9 @@ storage_decrypted_array_name :: (collection: string) -> string {
|
||||
if collection == MediaCollection {
|
||||
return "media_records"
|
||||
}
|
||||
if collection == EntityPhotosCollection {
|
||||
return "entity_photos"
|
||||
}
|
||||
if storage_compare_text(collection, "private.inbe.v1.habits") == 0 {
|
||||
return "habits"
|
||||
}
|
||||
|
||||
@@ -49,12 +49,22 @@ WHERE user_id=(SELECT id FROM users LIMIT 1) AND key GLOB 'cell.diary.chunk.*'
|
||||
ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at
|
||||
SQL_END;
|
||||
|
||||
// A sealed copy is its file plus a 16-byte tag; a photo from before copies
|
||||
// still costs its chunks.
|
||||
// Each sealed chunk is its plain bytes plus a 16-byte tag. A photo of the
|
||||
// account's entity data costs its chunks and its preview's; a Diary photo
|
||||
// that has not moved costs its old copy, and one from before copies its
|
||||
// hex chunks.
|
||||
SyncMediaLocalBytesSQL :: #string SQL_END
|
||||
SELECT COALESCE((SELECT SUM(json_extract(value,'$.size')+16) FROM settings
|
||||
WHERE user_id=(SELECT id FROM users LIMIT 1) AND key GLOB 'cell.diary.file.*'
|
||||
AND key NOT GLOB '*.json' AND json_valid(value) AND json_type(value,'$.count') IS NULL),0)
|
||||
SELECT COALESCE((SELECT SUM(json_extract(value,'$.size')+16*((json_extract(value,'$.size')+8388607)/8388608)
|
||||
+COALESCE(json_extract(value,'$.preview.size')+16*((json_extract(value,'$.preview.size')+8388607)/8388608),0))
|
||||
FROM settings
|
||||
WHERE user_id=(SELECT id FROM users LIMIT 1) AND key GLOB 'entity.photos.*' AND length(key)=78
|
||||
AND json_valid(value) AND json_type(value,'$.size')='integer'),0)
|
||||
+COALESCE((SELECT SUM(json_extract(d.value,'$.size')+16) FROM settings d
|
||||
WHERE d.user_id=(SELECT id FROM users LIMIT 1) AND d.key GLOB 'cell.diary.file.*'
|
||||
AND d.key NOT GLOB '*.json' AND json_valid(d.value) AND json_type(d.value,'$.count') IS NULL
|
||||
AND json_type(d.value,'$.photo') IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM settings e WHERE e.user_id=d.user_id
|
||||
AND e.key='entity.photos.'||json_extract(d.value,'$.hash'))),0)
|
||||
+COALESCE((SELECT SUM(125+LENGTH(key)+2*(LENGTH(key)+LENGTH(value)+73)) FROM settings
|
||||
WHERE user_id=(SELECT id FROM users LIMIT 1) AND key GLOB 'cell.diary.chunk.*'
|
||||
AND substr(key,18,64) IN (
|
||||
|
||||
@@ -114,6 +114,8 @@ storage_enqueue_all_sync_state :: () {
|
||||
exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'app_record',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND length(key) BETWEEN 73 AND 136 AND substr(key,1,7)='nested.' AND substr(key,8,64) NOT GLOB '*[^0-9a-f]*' AND substr(key,72,1)='.' AND substr(key,73) NOT GLOB '*[^a-z0-9.-]*' ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at")
|
||||
// The account's media library, in its own collection.
|
||||
exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'media_record',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key GLOB 'cell.media.?*' AND length(key)<=180 AND key NOT GLOB '*[^a-z0-9.-]*' ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at")
|
||||
// The account's entity data, shared by its apps.
|
||||
exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'entity_record',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND key GLOB 'entity.photos.*' AND length(key)=78 AND substr(key,15) NOT GLOB '*[^0-9a-f]*' AND json_valid(value) ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at")
|
||||
exec_sql("INSERT INTO sync_outbox(entity_type,entity_id,local_date,queued_at) SELECT 'cell_record',key,0,updated_at FROM settings WHERE user_id=(SELECT id FROM users LIMIT 1) AND (key LIKE 'cell.lumi.%' OR key LIKE 'cell.diary.%' OR key LIKE 'cell.feedback.%' OR key LIKE 'cell.achievement.%' OR key='notification_achievements') ON CONFLICT(entity_type,entity_id,local_date) DO UPDATE SET queued_at=excluded.queued_at")
|
||||
if owns_transaction != 0 {
|
||||
exec_sql("COMMIT")
|
||||
|
||||
@@ -7,11 +7,17 @@
|
||||
#import, file "storage_layout.zi";
|
||||
#import "crypto"
|
||||
#import "keys"
|
||||
#import "vec"
|
||||
#import "byte_text_linux"
|
||||
#import "text_buffer"
|
||||
#import, file "db.zi";
|
||||
#import, file "storage_core.zi";
|
||||
#import, file "storage_settings.zi";
|
||||
#import, file "sync_record_codec.zi";
|
||||
#import, file "sync_collections.zi";
|
||||
#import, file "entity_records.zi";
|
||||
#import, file "entity_record_crypto.zi";
|
||||
#import "daochi_client/entity"
|
||||
c :: #system_library "c";
|
||||
sqlite3_column_int :: (statement: *void, column: s32) -> s32 #foreign c "sqlite3_column_int";
|
||||
malloc :: (size: usize) -> *void #foreign c;
|
||||
@@ -41,6 +47,41 @@ storage_private_record_key_for_context :: (context: string, out: *u8) -> s32 {
|
||||
return ok
|
||||
}
|
||||
|
||||
// The account private key (the ML-DSA-44 secret key bytes) in output, which
|
||||
// the caller wipes; its length, or 0 without an owner's key on this device.
|
||||
storage_account_private_key :: (output: []u8) -> s64 {
|
||||
if storage_delegate_mode != null && storage_delegate_mode() == 2 {
|
||||
return 0
|
||||
}
|
||||
private_key_hex: string = storage_get_setting_text(STORAGE_SYNC_PRIVATE_KEY_KEY)
|
||||
key_size: s64 = (ACCOUNT_PRIVATE_KEY_HEX_SIZE - 1) / 2
|
||||
if private_key_hex.count != key_size * 2 || output.count < key_size {
|
||||
return 0
|
||||
}
|
||||
if HexToBytes(private_key_hex, *output[0], key_size) == 0 {
|
||||
SecureWipe(*output[0], key_size)
|
||||
return 0
|
||||
}
|
||||
return key_size
|
||||
}
|
||||
|
||||
// The record key of an entity collection, the same in every app of the
|
||||
// account (Daochi docs/entity-data.md).
|
||||
storage_entity_record_key :: (collection: string, out: *u8) -> s32 {
|
||||
private_key: [(ACCOUNT_PRIVATE_KEY_HEX_SIZE - 1) / 2]u8
|
||||
length := storage_account_private_key(private_key[:])
|
||||
defer { SecureWipe(*private_key[0], (ACCOUNT_PRIVATE_KEY_HEX_SIZE - 1) / 2) }
|
||||
kind := EntityCollectionKind(collection)
|
||||
if length == 0 || kind.count == 0 {
|
||||
return 0
|
||||
}
|
||||
if !EntityRecordKey(private_key[:length], kind, BytesFromPointer(out, 32)) {
|
||||
SecureWipe(out, 32)
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
storage_private_record_key :: (out: *u8) -> s32 {
|
||||
return storage_private_record_key_for_context(STORAGE_SYNC_RECORD_KEY_CONTEXT,
|
||||
out)
|
||||
@@ -71,6 +112,12 @@ storage_private_collection_key :: (collection: string, key_id: string, out: *u8)
|
||||
}
|
||||
return storage_private_record_key_for_context(LumiPrivateKeyContext, out)
|
||||
}
|
||||
if EntityCollectionKnown(collection) {
|
||||
if key_id != ENTITY_RECORD_KEY_ID {
|
||||
return 0
|
||||
}
|
||||
return storage_entity_record_key(collection, out)
|
||||
}
|
||||
if key_id != STORAGE_SYNC_RECORD_KEY_ID ||
|
||||
storage_decrypted_array_name(collection).count == 0 {
|
||||
return 0
|
||||
@@ -214,6 +261,94 @@ storage_append_encrypted_record_json :: (json: *StorageJsonBuilder, key: *u8, co
|
||||
return storage_encrypted_record_cleanup(*plain, *aad, sealed, sealed_hex, ok)
|
||||
}
|
||||
|
||||
// The account's public ID, the user_id_hash every app's associated data
|
||||
// names, in output.
|
||||
storage_entity_account_id :: (output: []u8) -> string {
|
||||
if !AppCopyText(storage_get_setting_text(STORAGE_SYNC_PUBLIC_ID_KEY), output) {
|
||||
return ""
|
||||
}
|
||||
return TextUntilNul(output)
|
||||
}
|
||||
|
||||
// An entity record goes out in Daochi's record profile, so every app of the
|
||||
// account reads it (entity_record_crypto.zi). Its plain text is the record's
|
||||
// own document, merged over its kept copy like every record, so fields
|
||||
// another app added stay. A record no longer on this device sends nothing.
|
||||
storage_append_entity_record_json :: (json: *StorageJsonBuilder, key: *u8, collection: string,
|
||||
record_id: string, entity_id: string, queued_at: s64) -> s32 {
|
||||
plain: StorageJsonBuilder
|
||||
plain.ok = 1
|
||||
defer { storage_json_builder_free(*plain) }
|
||||
statement: *void = null
|
||||
if SqlitePrepareText(storage_db_handle(), "SELECT value FROM settings WHERE user_id=?1 AND key=?2 AND json_valid(value)",
|
||||
-1, *statement, null) != SQLITE_OK {
|
||||
return 0
|
||||
}
|
||||
bind_text(statement, 1, AppTextFromCString(storage_user_id_buffer(), 64))
|
||||
bind_text(statement, 2, entity_id)
|
||||
if SqliteStep(statement) == SQLITE_ROW {
|
||||
storage_json_builder_append_text(*plain, AppTextFromCString(SqliteColumnText(statement, 0), ENTITY_RECORD_PLAIN_MAX))
|
||||
}
|
||||
SqliteFinalize(statement)
|
||||
if plain.ok == 0 {
|
||||
return 0
|
||||
}
|
||||
if plain.data == null || plain.len == 0 {
|
||||
return 2
|
||||
}
|
||||
storage_sync_record_merge(*plain, collection, record_id)
|
||||
if plain.ok == 0 || plain.data == null || plain.len == 0 {
|
||||
return 0
|
||||
}
|
||||
account: [65]u8
|
||||
metadata := EntityRecordMetadata.{.account_id = storage_entity_account_id(account[:]),
|
||||
.collection = collection, .id = record_id, .schema = EntityCollectionSchema(collection)}
|
||||
ciphertext: Vec(u8)
|
||||
nonce: Vec(u8)
|
||||
defer {
|
||||
VecFree(ciphertext)
|
||||
VecFree(nonce)
|
||||
}
|
||||
if !EntitySealRecord(key, metadata, BytesFromPointer(plain.data, cast(u64)plain.len), *ciphertext, *nonce) {
|
||||
return 0
|
||||
}
|
||||
storage_json_builder_append_text(json, "{")
|
||||
storage_json_builder_key_value_text(json, "collection", collection)
|
||||
storage_json_builder_append_text(json, ",")
|
||||
storage_json_builder_key_value_text(json, "id", record_id)
|
||||
storage_json_builder_append_text(json, ",")
|
||||
storage_json_builder_key_value_text(json, "key_id", ENTITY_RECORD_KEY_ID)
|
||||
storage_json_builder_append_text(json, ",")
|
||||
storage_json_builder_key_value_text(json, "nonce", TextFromBytes(VecSlice(nonce, 0, nonce.count)))
|
||||
storage_json_builder_append_text(json, ",")
|
||||
storage_json_builder_key_value_text(json, "ciphertext", TextFromBytes(VecSlice(ciphertext, 0, ciphertext.count)))
|
||||
storage_json_builder_append_text(json, ",\"updated_at\":")
|
||||
storage_json_builder_append_epoch(json, queued_at)
|
||||
storage_json_builder_append_text(json, ",\"schema_version\":1}")
|
||||
return json.ok
|
||||
}
|
||||
|
||||
// Opens an entity record that arrived in a sync reply: its plain text, to
|
||||
// free, through plaintext_out.
|
||||
storage_open_entity_record :: (collection: string, record_id: string, key_id: string,
|
||||
nonce: string, ciphertext: string, plaintext_out: **u8) -> s32 {
|
||||
plaintext_out.* = null
|
||||
key: [32]u8
|
||||
defer { SecureWipe(*key[0], 32) }
|
||||
if storage_private_collection_key(collection, key_id, *key[0]) == 0 {
|
||||
return 0
|
||||
}
|
||||
account: [65]u8
|
||||
metadata := EntityRecordMetadata.{.account_id = storage_entity_account_id(account[:]),
|
||||
.collection = collection, .id = record_id, .schema = EntityCollectionSchema(collection)}
|
||||
plain: *u8 = null
|
||||
if EntityOpenRecord(*key[0], metadata, key_id, nonce, ciphertext, *plain) < 0 {
|
||||
return 0
|
||||
}
|
||||
plaintext_out.* = plain
|
||||
return 1
|
||||
}
|
||||
|
||||
storage_append_encrypted_records_json :: (json: *StorageJsonBuilder, through_seq: s64) {
|
||||
stmt: *void = null
|
||||
key: [32] u8
|
||||
@@ -245,14 +380,34 @@ storage_append_encrypted_records_json :: (json: *StorageJsonBuilder, through_seq
|
||||
json.ok = 0
|
||||
break
|
||||
}
|
||||
if first == 0 {
|
||||
storage_json_builder_append_text(json, ",")
|
||||
}
|
||||
first = 0
|
||||
if storage_private_collection_key(collection, key_id, *key[0]) == 0 {
|
||||
json.ok = 0
|
||||
break
|
||||
}
|
||||
if EntityCollectionKnown(collection) {
|
||||
record: StorageJsonBuilder
|
||||
record.ok = 1
|
||||
appended := storage_append_entity_record_json(*record, *key[0], collection,
|
||||
AppTextFromCString(*record_id[0], 180), entity_id, queued_at)
|
||||
if appended == 1 && record.data != null {
|
||||
if first == 0 {
|
||||
storage_json_builder_append_text(json, ",")
|
||||
}
|
||||
first = 0
|
||||
storage_json_builder_append_text(json, AppTextFromCString(record.data, cast(s32)(record.len + 1)))
|
||||
}
|
||||
storage_json_builder_free(*record)
|
||||
SecureWipe(*key[0], 32)
|
||||
if appended == 0 {
|
||||
json.ok = 0
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
if first == 0 {
|
||||
storage_json_builder_append_text(json, ",")
|
||||
}
|
||||
first = 0
|
||||
if storage_append_encrypted_record_json(json, *key[0], collection, key_id, AppTextFromCString(*record_id[0], 180),
|
||||
entity_type, entity_id, local_date,
|
||||
queued_at, is_delete) == 0 {
|
||||
|
||||
@@ -255,6 +255,21 @@ OR (excluded.updated_at = settings.updated_at AND excluded.value != settings.val
|
||||
))
|
||||
SQL
|
||||
|
||||
// One entity record of the account (storage/entity_records.zi), checked
|
||||
// first. Fields only this device has stay; a change not sent yet keeps
|
||||
// this device's record until it goes out.
|
||||
SyncEntityRecordSQL :: #string SQL
|
||||
INSERT INTO settings(user_id,key,value,updated_at)
|
||||
VALUES(?1,?2,json(?3),COALESCE(CAST(strftime('%s',NULLIF(?4,'')) AS INTEGER),CAST(strftime('%s','now') AS INTEGER)))
|
||||
ON CONFLICT(user_id,key) DO UPDATE SET
|
||||
value=CASE WHEN json_valid(settings.value) THEN json_patch(settings.value,excluded.value) ELSE excluded.value END,
|
||||
updated_at=excluded.updated_at
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM sync_outbox WHERE entity_type='entity_record'
|
||||
AND entity_id=settings.key AND local_date=0
|
||||
) AND (NOT json_valid(settings.value) OR json_patch(settings.value,excluded.value) != settings.value)
|
||||
SQL
|
||||
|
||||
SyncCellRecordsSQL :: #string SQL
|
||||
INSERT INTO settings(user_id,key,value,updated_at)
|
||||
SELECT ?2,json_extract(value,'$.key'),json_extract(value,'$.value'),
|
||||
|
||||
+86
-97
@@ -91,6 +91,7 @@ Dates :: #import, file "../apps/diary/diary_date.zi";
|
||||
#import, file "../src/cells/diary_photos.zi";
|
||||
#import, file "../src/cells/media_store.zi";
|
||||
#import, file "../src/cells/media_diary_photos.zi";
|
||||
#import, file "../src/cells/entity_photos.zi";
|
||||
#import, file "../src/storage/cell_records.zi";
|
||||
#import, file "../src/cells/package_files.zi";
|
||||
#import, file "../src/app/app_types.zi";
|
||||
@@ -509,15 +510,13 @@ DiaryTestHash :: (data: []u8, output: []u8) -> string {
|
||||
return TextFromCString(*output[0])
|
||||
}
|
||||
|
||||
// The pass's job for one photo, on any node or on the node at `node`, or 0;
|
||||
// other Diary tests leave photos too.
|
||||
DiaryTestNodeJob :: (pass: *DiaryBlobPass, name: string, node: string) -> s32 {
|
||||
key := DiaryRecordKey(name)
|
||||
defer { PackageFree(key) }
|
||||
// The pass's job for one photo's original, on any node or on the node at
|
||||
// `node`, or 0; other Diary tests leave photos too.
|
||||
DiaryTestNodeJob :: (pass: *DiaryBlobPass, key: string, node: string) -> s32 {
|
||||
for index: cast(s32)0..pass.count - 1 {
|
||||
address: [256]u8
|
||||
unused DiaryBlobNode(pass, pass.jobs[index].node, address[:])
|
||||
if TextUntilNul(pass.jobs[index].key[:]) == key &&
|
||||
if TextUntilNul(pass.jobs[index].key[:]) == key && !pass.jobs[index].preview &&
|
||||
(node.count == 0 || TextUntilNul(address[:]) == node) {
|
||||
return pass.jobs[index].kind
|
||||
}
|
||||
@@ -525,31 +524,36 @@ DiaryTestNodeJob :: (pass: *DiaryBlobPass, name: string, node: string) -> s32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
DiaryTestJob :: (pass: *DiaryBlobPass, name: string) -> s32 {
|
||||
return DiaryTestNodeJob(pass, name, "")
|
||||
DiaryTestJob :: (pass: *DiaryBlobPass, key: string) -> s32 {
|
||||
return DiaryTestNodeJob(pass, key, "")
|
||||
}
|
||||
|
||||
// The pass's request for one photo, skipping the others.
|
||||
DiaryTestNext :: (pass: *DiaryBlobPass, request: *DiaryBlobRequest, name: string) -> bool {
|
||||
key := DiaryRecordKey(name)
|
||||
defer { PackageFree(key) }
|
||||
// The pass's request for one photo's original, skipping the others.
|
||||
DiaryTestNext :: (pass: *DiaryBlobPass, request: *DiaryBlobRequest, key: string) -> bool {
|
||||
while DiaryBlobNext(pass, request) {
|
||||
if TextUntilNul(request.key[:]) == key {
|
||||
if TextUntilNul(request.key[:]) == key && !request.preview {
|
||||
return true
|
||||
}
|
||||
DiaryBlobAbandon(request)
|
||||
DiaryBlobJobDone(pass)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// A photo is its file: only its entry syncs, and its sealed copy, the file's
|
||||
// size plus 16 bytes, travels to a node and back to the account's devices.
|
||||
DiaryTestChunks :: (hash: string) -> EntityContent {
|
||||
record := MediaEntityRecord(hash)
|
||||
defer { PackageFree(record) }
|
||||
return EntityPhotoContent(record)
|
||||
}
|
||||
|
||||
// A photo travels as the account's entity data, sealed in chunks of its
|
||||
// size plus 16 bytes, to a node and back to the account's devices.
|
||||
CheckDiaryPhotoCopies :: () {
|
||||
node := "https://copies.test"
|
||||
sync_was_enabled := storage_sync_enabled()
|
||||
storage_set_sync_enabled(1)
|
||||
storage_set_setting_text("sync_server_url", node)
|
||||
// The account key lets this device seal copies.
|
||||
// The account key lets this device seal chunks.
|
||||
private: [5121]u8
|
||||
for index: cast(s32)0..cast(s32)5119 {
|
||||
private[index] = ifx index % 2 == 0 then #char "a" else #char "7"
|
||||
@@ -557,45 +561,44 @@ CheckDiaryPhotoCopies :: () {
|
||||
storage_set_setting_text(STORAGE_SYNC_PRIVATE_KEY_KEY, TextFromBytes(private[:5120]))
|
||||
png: [3000]u8
|
||||
image := DiaryTestImage(png[:], 3)
|
||||
source := "copied-photo.png"
|
||||
unused RemoveFile(source)
|
||||
file := OpenExclusivePrivate(source)
|
||||
written := file.valid && WriteTextAt(file, image, 0) == image.count
|
||||
Expect(CloseFile(file) && written, 430)
|
||||
name := DiaryStoreAttach(source)
|
||||
unused RemoveFile(source)
|
||||
Expect(name.count > 0, 431)
|
||||
media := DiaryMediaRead(name)
|
||||
added := MediaImportBytes(image, "copied-photo.png")
|
||||
Expect(added.succeeded && !added.existed, 430)
|
||||
hash_text: [65]u8
|
||||
hash := DiaryTestHash(png[:], hash_text[:])
|
||||
Expect(media.valid && !DiaryMediaUploaded(media) && media.size == 3000 &&
|
||||
TextFromBytes(media.hash[:64]) == hash, 432)
|
||||
no_chunks := PackageText(PackageText("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.diary.chunk.", hash), ".*'")
|
||||
Expect(ModuleTestCount(no_chunks) == 0, 433)
|
||||
PackageFree(no_chunks)
|
||||
// A pass seals and uploads it, then its entry names the copy.
|
||||
key := EntityPhotoKey(hash)
|
||||
Expect(TextFromBytes(added.hash[:64]) == hash, 431)
|
||||
content := DiaryTestChunks(hash)
|
||||
Expect(content.valid && content.chunk_count == 0 && content.size == 3000, 432)
|
||||
no_copies := PackageText(PackageText("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.diary.chunk.", hash), ".*' OR key GLOB 'cell.media.*'")
|
||||
Expect(ModuleTestCount(no_copies) == 0, 433)
|
||||
PackageFree(no_copies)
|
||||
// A pass seals and uploads it, then its record names the chunk.
|
||||
pass: DiaryBlobPass
|
||||
request: DiaryBlobRequest
|
||||
Expect(DiaryBlobPlan(*pass, node) && DiaryTestJob(*pass, name) == DIARY_BLOB_UPLOAD, 434)
|
||||
Expect(DiaryTestNext(*pass, *request, name) && request.method == "PUT" &&
|
||||
request.body.count == image.count + DIARY_BLOB_TAG && request.body != image, 435)
|
||||
Expect(DiaryBlobPlan(*pass, node) && DiaryTestJob(*pass, key) == DIARY_BLOB_UPLOAD, 434)
|
||||
Expect(DiaryTestNext(*pass, *request, key) && request.method == "PUT" &&
|
||||
request.body.count == image.count + 16 && request.body != image, 435)
|
||||
sealed := PackageText(request.body, "")
|
||||
blob_text: [65]u8
|
||||
blob := DiaryTestHash(DiaryTestBytes(sealed), blob_text[:])
|
||||
blob_path := PackageText("/api/v1/blobs/inbe/", blob)
|
||||
blob_path := PackageText("/api/v1/blobs/entity/", blob)
|
||||
Expect(TextUntilNul(request.path[:]) == blob_path, 436)
|
||||
Expect(DiaryBlobFinish(*pass, *request, 204, png[0:0]), 437)
|
||||
media = DiaryMediaRead(name)
|
||||
Expect(DiaryMediaUploaded(media) && TextFromBytes(media.blob[:64]) == blob, 438)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
content = DiaryTestChunks(hash)
|
||||
Expect(content.chunk_count == 1 && TextUntilNul(content.chunks[0].address[:]) == blob &&
|
||||
content.chunks[0].size == 3016, 438)
|
||||
unused DiaryBlobPlan(*pass, node)
|
||||
Expect(DiaryTestJob(*pass, name) == 0, 439)
|
||||
// Another device of the account has only the entry: the photo shows as
|
||||
// not on the device until its copy arrives, opened and checked.
|
||||
path := DiaryStorePath(name)
|
||||
Expect(DiaryTestJob(*pass, key) == 0, 439)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
// Another device of the account has only the record: the photo is not
|
||||
// on the device until its chunks arrive, opened and checked.
|
||||
path := MediaPath(hash, false)
|
||||
unused RemoveFile(path)
|
||||
Expect(!DiaryStoreRead(name).succeeded && DiaryStorePreview(name).count == 0, 440)
|
||||
Expect(DiaryBlobPlan(*pass, node) && DiaryTestJob(*pass, name) == DIARY_BLOB_DOWNLOAD, 441)
|
||||
Expect(DiaryTestNext(*pass, *request, name) && request.method == "GET" &&
|
||||
MediaWant(hash)
|
||||
Expect(!PathExists(path), 440)
|
||||
Expect(DiaryBlobPlan(*pass, node) && DiaryTestJob(*pass, key) == DIARY_BLOB_DOWNLOAD, 441)
|
||||
Expect(DiaryTestNext(*pass, *request, key) && request.method == "GET" &&
|
||||
request.answer_bytes == sealed.count + 1, 442)
|
||||
tampered := PackageText(sealed, "")
|
||||
changed := DiaryTestBytes(tampered)
|
||||
@@ -603,65 +606,51 @@ CheckDiaryPhotoCopies :: () {
|
||||
generation := diary_blob_generation
|
||||
Expect(DiaryBlobFinish(*pass, *request, 200, changed) &&
|
||||
!PathExists(path) && diary_blob_generation == generation, 443)
|
||||
Expect(DiaryBlobFinish(*pass, *request, 404, png[0:0]) && !PathExists(path), 444)
|
||||
Expect(DiaryBlobFinish(*pass, *request, 200, DiaryTestBytes(sealed)) &&
|
||||
diary_blob_generation > generation, 445)
|
||||
Expect(DiaryStoreRead(name).data == image && DiaryStorePreview(name) == image, 446)
|
||||
// A new node gets the same copy once.
|
||||
DiaryBlobPassEnd(*pass)
|
||||
Expect(DiaryBlobPlan(*pass, node) && DiaryTestNext(*pass, *request, key) &&
|
||||
DiaryBlobFinish(*pass, *request, 404, png[0:0]) && !PathExists(path), 444)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
Expect(DiaryBlobPlan(*pass, node) && DiaryTestNext(*pass, *request, key) &&
|
||||
DiaryBlobFinish(*pass, *request, 200, DiaryTestBytes(sealed)) && diary_blob_generation > generation, 445)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
Expect(PackageRead(path, DIARY_FILE_LIMIT) == image, 446)
|
||||
// A new node gets the same chunk once.
|
||||
other := "https://other-copies.test"
|
||||
Expect(DiaryBlobPlan(*pass, other) && DiaryTestJob(*pass, name) == DIARY_BLOB_UPLOAD, 447)
|
||||
Expect(DiaryTestNext(*pass, *request, name) && request.body == sealed, 448)
|
||||
Expect(DiaryBlobPlan(*pass, other) && DiaryTestNodeJob(*pass, key, other) == DIARY_BLOB_UPLOAD, 447)
|
||||
while DiaryTestNext(*pass, *request, key) && TextUntilNul(request.node[:]) != other {
|
||||
DiaryBlobAbandon(*request)
|
||||
DiaryBlobJobDone(*pass)
|
||||
}
|
||||
Expect(request.body == sealed, 448)
|
||||
Expect(DiaryBlobFinish(*pass, *request, 204, png[0:0]), 449)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
unused DiaryBlobPlan(*pass, other)
|
||||
Expect(DiaryTestJob(*pass, name) == 0, 459)
|
||||
Expect(DiaryTestNodeJob(*pass, key, other) == 0, 459)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
// A node without photo upload receives none; a full one stops uploads
|
||||
// to it alone.
|
||||
third := "https://third-copies.test"
|
||||
Expect(SyncNodeSetMediaUpload(third, false) && DiaryBlobPlan(*pass, third) &&
|
||||
DiaryTestNodeJob(*pass, name, third) == 0, 450)
|
||||
Expect(SyncNodeSetMediaUpload(third, false), 450)
|
||||
unused DiaryBlobPlan(*pass, third)
|
||||
Expect(DiaryTestNodeJob(*pass, key, third) == 0, 450)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
Expect(SyncNodeSetMediaUpload(third, true) && DiaryBlobPlan(*pass, third) &&
|
||||
DiaryTestNodeJob(*pass, name, third) == DIARY_BLOB_UPLOAD && DiaryTestNext(*pass, *request, name), 451)
|
||||
DiaryTestNodeJob(*pass, key, third) == DIARY_BLOB_UPLOAD, 451)
|
||||
while DiaryTestNext(*pass, *request, key) && TextUntilNul(request.node[:]) != third {
|
||||
DiaryBlobAbandon(*request)
|
||||
DiaryBlobJobDone(*pass)
|
||||
}
|
||||
full := "{\"code\":\"storage_full\",\"account_storage\":{\"used_bytes\":20971000,\"limit_bytes\":20971520}}"
|
||||
full_text := PackageText(full, "")
|
||||
Expect(DiaryBlobFinish(*pass, *request, 413, DiaryTestBytes(full_text)) &&
|
||||
pass.stopped[request.node_index] && SyncNodeStorageRead(third).full, 452)
|
||||
DiaryBlobPassEnd(*pass)
|
||||
PackageFree(full_text)
|
||||
// A photo from before copies, kept as hex chunks, uploads the same copy
|
||||
// and its chunks shrink to one byte each.
|
||||
older: [2500]u8
|
||||
old_image := DiaryTestImage(older[:], 9)
|
||||
old_name := "photo-20240301000000-1.bin"
|
||||
old_hash_text: [65]u8
|
||||
old_hash := DiaryTestHash(older[:], old_hash_text[:])
|
||||
for index: cast(s32)0..2 {
|
||||
start := index * 1024
|
||||
size: s32 = 1024
|
||||
if start + size > 2500 {
|
||||
size = 2500 - start
|
||||
}
|
||||
hex: [2049]u8
|
||||
unused BytesToHex(*older[start], cast(s64)size, *hex[0], 2049)
|
||||
chunk := DiaryChunkKey(old_hash, index)
|
||||
Expect(CellRecordWrite(chunk, TextFromCString(*hex[0])), 453)
|
||||
PackageFree(chunk)
|
||||
}
|
||||
old_entry := PackageText(PackageText("{\"hash\":\"", old_hash), "\",\"count\":3,\"size\":2500}")
|
||||
old_key := DiaryRecordKey(old_name)
|
||||
Expect(CellRecordWrite(old_key, old_entry) && DiaryStoreRead(old_name).data == old_image, 454)
|
||||
Expect(DiaryBlobPlan(*pass, node) && DiaryTestJob(*pass, old_name) == DIARY_BLOB_UPLOAD &&
|
||||
DiaryTestNext(*pass, *request, old_name) && request.chunked && request.body.count == 2500 + DIARY_BLOB_TAG, 455)
|
||||
Expect(DiaryBlobFinish(*pass, *request, 204, png[0:0]) && DiaryMediaUploaded(DiaryMediaRead(old_name)), 456)
|
||||
shrunk := PackageText(PackageText("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.diary.chunk.", old_hash), ".*' AND value='-'")
|
||||
Expect(ModuleTestCount(shrunk) == 3, 457)
|
||||
PackageFree(shrunk)
|
||||
Expect(DiaryStoreRead(old_name).data == old_image, 458)
|
||||
PackageFree(old_key)
|
||||
PackageFree(old_entry)
|
||||
PackageFree(tampered)
|
||||
PackageFree(blob_path)
|
||||
PackageFree(sealed)
|
||||
PackageFree(path)
|
||||
PackageFree(name)
|
||||
PackageFree(key)
|
||||
storage_set_setting_text(STORAGE_SYNC_PRIVATE_KEY_KEY, "")
|
||||
storage_set_setting_text("sync_server_url", "")
|
||||
storage_set_sync_enabled(sync_was_enabled)
|
||||
@@ -689,15 +678,13 @@ DiaryLibraryRun :: () {
|
||||
}
|
||||
|
||||
DiaryLibraryRecord :: (hash: string) -> string {
|
||||
key := MediaRecordKey(hash)
|
||||
defer { PackageFree(key) }
|
||||
return MediaRecordRead(key)
|
||||
return MediaEntityRecord(hash)
|
||||
}
|
||||
|
||||
// Photos older versions attached to Diary entries join the media library,
|
||||
// which Photos shows, under the entry's day and with the entry's name. A
|
||||
// Diary file no entry includes stays out, a photo in Trash stays there, and
|
||||
// looking again changes nothing.
|
||||
// Photos older versions attached to Diary entries move to the account's
|
||||
// entity data, which Photos shows, under the entry's day and with the
|
||||
// entry's name. A Diary file no entry includes stays out, a photo in Trash
|
||||
// stays there, and looking again changes nothing.
|
||||
CheckDiaryPhotosInLibrary :: () {
|
||||
first: [2600]u8
|
||||
second: [2700]u8
|
||||
@@ -753,8 +740,9 @@ CheckDiaryPhotosInLibrary :: () {
|
||||
Expect(!MediaRead(orphan_hash).valid && !MediaRead(later_hash).valid, 487)
|
||||
trashed_now := DiaryLibraryRecord(trashed_hash)
|
||||
Expect(trashed_now == trashed_record && MediaRead(trashed_hash).trashed, 488)
|
||||
// Diary files of other checks belong to no entry either.
|
||||
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.media.*' AND length(key)=75") == 3, 489)
|
||||
// Diary files of other checks belong to no entry either; the photo the
|
||||
// copies check added is the fourth.
|
||||
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*' AND length(key)=78") == 4, 489)
|
||||
Expect(DiaryStoreRead("2024-04-02.json").data == first_entry &&
|
||||
DiaryStoreRead("2024-04-03.json").data == second_entry, 490)
|
||||
// The entry's Diary file draws as the library's photo, so Diary's day
|
||||
@@ -784,7 +772,8 @@ CheckDiaryPhotosInLibrary :: () {
|
||||
trashed_again := DiaryLibraryRecord(trashed_hash)
|
||||
Expect(first_again == first_record && second_again == second_record && later_again == later_record &&
|
||||
trashed_again == trashed_record, 494)
|
||||
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.media.*' AND length(key)=75") == 4, 495)
|
||||
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*' AND length(key)=78") == 5, 495)
|
||||
Expect(ModuleTestCount("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.media.*'") == 0, 499)
|
||||
// The library's file is the Diary file, linked, not a second copy: a
|
||||
// byte changed in place in one shows in the other.
|
||||
diary_path := DiaryStorePath(first_name)
|
||||
|
||||
@@ -79,8 +79,13 @@ def ink_bottom(path, box):
|
||||
|
||||
|
||||
def library_has(profile, digest):
|
||||
"""Whether the profile's photo library keeps the photo with this hash."""
|
||||
return bool(list((profile / "media").glob("*/" + digest)))
|
||||
"""Whether the profile's photo library keeps the photo with this hash:
|
||||
its file, and its record in the account's entity data."""
|
||||
if not list((profile / "media").glob("*/" + digest)):
|
||||
return False
|
||||
with sqlite3.connect(profile / "inbe.db", timeout=3) as database:
|
||||
return database.execute("select count(*) from settings where key=?",
|
||||
("entity.photos." + digest,)).fetchone()[0] == 1
|
||||
|
||||
|
||||
def wait_for_text(entry, matches, message):
|
||||
|
||||
@@ -0,0 +1,557 @@
|
||||
// A profile Inbe 2.1.43 left (fixtures/photos-2.1.43.sql, made by
|
||||
// fixtures/make_photos_fixture.py) upgrades: its Diary and library photos
|
||||
// move to the account's entity data, and nothing is lost on the way.
|
||||
// Every photo stays listed and drawn throughout. An old copy goes only
|
||||
// after the sync node confirmed the photo's record and chunks and they came
|
||||
// back whole; an interrupted pass, a full node, an unreachable node, a node
|
||||
// that cannot delete yet and a damaged chunk each keep the old copies for a
|
||||
// later pass. Released versions keep reading every old record. A delegate
|
||||
// device moves nothing, and the account's other device draws each moved
|
||||
// photo from its entity record alone. The nodes here answer from memory.
|
||||
#import "byte_text_linux"
|
||||
#import "vec"
|
||||
#import "text"
|
||||
#import "file_linux"
|
||||
#import "json_scan"
|
||||
#import "text_buffer"
|
||||
#import "crypto"
|
||||
#import "keys"
|
||||
#import, file "storage_test_support.zi";
|
||||
#import, file "../src/app/text_buffers.zi";
|
||||
#import, file "../src/storage/data.zi";
|
||||
#import, file "../src/storage/state.zi";
|
||||
#import, file "../src/storage/db.zi";
|
||||
#import, file "../src/storage/storage_core.zi";
|
||||
#import, file "../src/storage/storage_settings.zi";
|
||||
#import, file "../src/storage/media_records.zi";
|
||||
#import, file "../src/storage/entity_records.zi";
|
||||
#import, file "../src/storage/sync_exchange.zi";
|
||||
#import, file "../src/storage/sync_outbox.zi";
|
||||
#import, file "../src/storage/sync_apply.zi";
|
||||
#import, file "../src/storage/sync_nodes.zi";
|
||||
#import, file "../src/storage/sync_node_storage.zi";
|
||||
#import, file "../src/storage/sqlite.zi";
|
||||
#import, file "../src/storage/paths.zi";
|
||||
#import, file "../src/cells/package_files.zi";
|
||||
#import, file "../src/cells/diary_records.zi";
|
||||
#import, file "../src/cells/diary_store.zi";
|
||||
#import, file "../src/cells/diary_photos.zi";
|
||||
#import, file "../src/cells/diary_blobs.zi";
|
||||
#import, file "../src/cells/entity_photos.zi";
|
||||
#import, file "../src/cells/media_store.zi";
|
||||
#import, file "../src/cells/media_diary_photos.zi";
|
||||
|
||||
entity_test_c :: #system_library "c";
|
||||
EnvironmentText :: (name: *u8) -> *u8 #foreign entity_test_c "getenv";
|
||||
FixtureOpen :: (path: *u8, db: **void) -> s32 #foreign entity_test_c "sqlite3_open";
|
||||
FixtureExec :: (db: *void, sql: *u8, callback: *void, argument: *void, error: **u8) -> s32 #foreign entity_test_c "sqlite3_exec";
|
||||
FixtureClose :: (db: *void) -> s32 #foreign entity_test_c "sqlite3_close";
|
||||
|
||||
FIXTURE_SYNC_NODE :: "https://sync.photos.test"
|
||||
FIXTURE_OTHER_NODE :: "https://other.photos.test"
|
||||
FIXTURE_ACCOUNT :: "7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d"
|
||||
WALK_FILE :: "photo-20240402081500-1.bin"
|
||||
TEA_FILE :: "photo-20240403090000-1.bin"
|
||||
RAIN_FILE :: "photo-20240301000000-1.bin"
|
||||
ORPHAN_FILE :: "photo-20240405000000-1.bin"
|
||||
|
||||
// PNG's signature, then (index * 7 + seed) % 251, as the fixture's photos.
|
||||
FixturePhoto :: (size: s64, seed: s64) -> string {
|
||||
out: Vec(u8)
|
||||
header: [8]u8 = .[cast(u8)137, cast(u8)80, cast(u8)78, cast(u8)71, cast(u8)13, cast(u8)10, cast(u8)26, cast(u8)10]
|
||||
for index: cast(s64)0..size - 1 {
|
||||
unused VecPush(out, ifx index < 8 then header[index] else cast(u8)((index * 7 + seed) % 251))
|
||||
}
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
Hash :: (data: string) -> string {
|
||||
output: [65]u8
|
||||
descriptor := cast(*TextDescriptor)(*data)
|
||||
storage_sha256_hex(descriptor.data, data.count, *output[0])
|
||||
return PackageText(TextFromCString(*output[0]), "")
|
||||
}
|
||||
|
||||
// What the nodes hold and how they answer.
|
||||
FakeBlob :: struct {
|
||||
node: [64]u8
|
||||
address: [65]u8
|
||||
bytes: string
|
||||
}
|
||||
|
||||
FakeNode :: struct {
|
||||
address: [64]u8
|
||||
// Deletes answer 405, as a node from before deletes.
|
||||
no_deletes: bool
|
||||
// Uploads answer 413.
|
||||
full: bool
|
||||
// Nothing answers.
|
||||
offline: bool
|
||||
}
|
||||
|
||||
FAKE_BLOBS :: 64
|
||||
fake_blobs: [FAKE_BLOBS]FakeBlob;
|
||||
fake_blob_count: s32;
|
||||
fake_nodes: [2]FakeNode;
|
||||
fake_requests: s32;
|
||||
fake_puts: s32;
|
||||
fake_deletes: s32;
|
||||
|
||||
FakeFind :: (node: string, address: string) -> s32 {
|
||||
for index: cast(s32)0..fake_blob_count - 1 {
|
||||
blob := *fake_blobs[index]
|
||||
if blob.bytes.count > 0 && TextUntilNul(blob.node[:]) == node && TextUntilNul(blob.address[:]) == address {
|
||||
return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
FakeHas :: (node: string, address: string) -> bool {
|
||||
return FakeFind(node, address) >= 0
|
||||
}
|
||||
|
||||
FakeStore :: (node: string, address: string, bytes: string) {
|
||||
at := FakeFind(node, address)
|
||||
if at < 0 {
|
||||
at = fake_blob_count
|
||||
fake_blob_count += 1
|
||||
}
|
||||
check_true("the fake nodes have room", at < FAKE_BLOBS)
|
||||
blob := *fake_blobs[at]
|
||||
unused AppCopyText(node, blob.node[:])
|
||||
unused AppCopyText(address, blob.address[:])
|
||||
blob.bytes = PackageText(bytes, "")
|
||||
}
|
||||
|
||||
FakeNodeOf :: (address: string) -> *FakeNode {
|
||||
if TextUntilNul(fake_nodes[1].address[:]) == address {
|
||||
return *fake_nodes[1]
|
||||
}
|
||||
return *fake_nodes[0]
|
||||
}
|
||||
|
||||
// The old copies the fixture's nodes hold.
|
||||
FakeLoadFixture :: () {
|
||||
statement: *void
|
||||
check_true("read the fixture's nodes", SqlitePrepareText(storage_db_handle(),
|
||||
"SELECT node,address,bytes FROM fixture_node_blobs", -1, *statement, null) == SQLITE_OK)
|
||||
while SqliteStep(statement) == SQLITE_ROW {
|
||||
hex := AppTextFromCString(SqliteColumnText(statement, 2), 65536)
|
||||
out: Vec(u8)
|
||||
for index: cast(s64)0..hex.count / 2 - 1 {
|
||||
unused VecPush(out, cast(u8)0)
|
||||
}
|
||||
bytes := BuilderFinish(out)
|
||||
descriptor := cast(*TextDescriptor)(*bytes)
|
||||
unused HexToBytes(hex, descriptor.data, bytes.count)
|
||||
FakeStore(AppTextFromCString(SqliteColumnText(statement, 0), 64),
|
||||
AppTextFromCString(SqliteColumnText(statement, 1), 65), bytes)
|
||||
PackageFree(bytes)
|
||||
}
|
||||
SqliteFinalize(statement)
|
||||
}
|
||||
|
||||
// One pass, as the host runs it, of at most `limit` requests: the nodes
|
||||
// answer from memory. The answer: the requests sent.
|
||||
RunPass :: (limit: s32) -> s32 {
|
||||
pass: DiaryBlobPass
|
||||
sent: s32 = 0
|
||||
if !DiaryBlobPlan(*pass, FIXTURE_SYNC_NODE) {
|
||||
return 0
|
||||
}
|
||||
request: DiaryBlobRequest
|
||||
while sent < limit && DiaryBlobNext(*pass, *request) {
|
||||
sent += 1
|
||||
fake_requests += 1
|
||||
node := TextUntilNul(request.node[:])
|
||||
fake := FakeNodeOf(node)
|
||||
path := TextUntilNul(request.path[:])
|
||||
address := path[path.count - 64:]
|
||||
if fake.offline {
|
||||
DiaryBlobFailed(*pass, *request)
|
||||
DiaryBlobAbandon(*request)
|
||||
continue
|
||||
}
|
||||
status: s32 = 404
|
||||
answer := ""
|
||||
if request.method == "PUT" {
|
||||
status = ifx fake.full then cast(s32)413 else cast(s32)204
|
||||
if !fake.full {
|
||||
FakeStore(node, address, request.body)
|
||||
fake_puts += 1
|
||||
}
|
||||
} else if request.method == "DELETE" {
|
||||
status = ifx fake.no_deletes then cast(s32)405 else cast(s32)204
|
||||
at := FakeFind(node, address)
|
||||
if !fake.no_deletes && at >= 0 {
|
||||
PackageFree(fake_blobs[at].bytes)
|
||||
fake_blobs[at].bytes = ""
|
||||
fake_deletes += 1
|
||||
}
|
||||
} else {
|
||||
at := FakeFind(node, address)
|
||||
if at >= 0 {
|
||||
status = 200
|
||||
answer = fake_blobs[at].bytes
|
||||
}
|
||||
}
|
||||
if status == 413 {
|
||||
answer = "{\"code\":\"storage_full\",\"account_storage\":{\"used_bytes\":20971000,\"limit_bytes\":20971520}}"
|
||||
}
|
||||
descriptor := cast(*TextDescriptor)(*answer)
|
||||
unused DiaryBlobFinish(*pass, *request, status, BytesFromPointer(descriptor.data, cast(u64)answer.count))
|
||||
DiaryBlobAbandon(*request)
|
||||
}
|
||||
DiaryBlobPassEnd(*pass)
|
||||
return sent
|
||||
}
|
||||
|
||||
// Passes until one sends nothing.
|
||||
RunPasses :: () {
|
||||
for round: 0..20 {
|
||||
unused round
|
||||
if RunPass(1000) == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MoveSteps :: () {
|
||||
MediaDiaryPhotosDue()
|
||||
for step: 0..80 {
|
||||
unused step
|
||||
unused MediaDiaryPhotosStep()
|
||||
}
|
||||
}
|
||||
|
||||
// Good syncs: every queued record goes to the sync node, which keeps it,
|
||||
// batch after batch.
|
||||
GoodSync :: () {
|
||||
for batch: 0..20 {
|
||||
unused batch
|
||||
payload := storage_build_sync_payload_json(FIXTURE_ACCOUNT, "fixture-public-key")
|
||||
check_true("a sync payload builds", payload != null)
|
||||
storage_free_sync_payload_json(payload)
|
||||
storage_clear_uploaded_outbox(storage_state_handle().pending_sync_outbox_seq)
|
||||
if storage_has_pending_sync_outbox() == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
check_int("the node has every record", storage_has_pending_sync_outbox(), 0)
|
||||
MediaDiaryPhotosDue()
|
||||
}
|
||||
|
||||
Setting :: (key: string) -> string {
|
||||
return PackageText(storage_get_setting_text(key), "")
|
||||
}
|
||||
|
||||
EntityField :: (hash: string, field: string) -> string {
|
||||
sql := PackageText(PackageText(PackageText("SELECT COALESCE(json_extract(value,'$.", field), "'),'') FROM settings WHERE key='entity.photos."),
|
||||
PackageText(hash, "'"))
|
||||
defer { PackageFree(sql) }
|
||||
return PackageText(read_db_text(sql), "")
|
||||
}
|
||||
|
||||
Count :: (sql: string) -> s32 {
|
||||
return read_db_count(sql)
|
||||
}
|
||||
|
||||
// The first column of the query's first row, whole, to free.
|
||||
ReadText :: (sql: string) -> string {
|
||||
statement: *void
|
||||
if SqlitePrepareText(storage_db_handle(), sql, -1, *statement, null) != SQLITE_OK {
|
||||
return ""
|
||||
}
|
||||
defer { SqliteFinalize(statement) }
|
||||
if SqliteStep(statement) != SQLITE_ROW {
|
||||
return ""
|
||||
}
|
||||
return PackageText(AppTextFromCString(SqliteColumnText(statement, 0), 1048576), "")
|
||||
}
|
||||
|
||||
// Every record a released version reads, whole: the Diary's and the
|
||||
// library's.
|
||||
OldRecords :: () -> string {
|
||||
return ReadText("SELECT group_concat(key||'='||value,'|') FROM (SELECT key,value FROM settings WHERE key GLOB 'cell.diary.*' OR key GLOB 'cell.media.*' ORDER BY key)")
|
||||
}
|
||||
|
||||
LoadFixture :: (root: string) {
|
||||
path: TextBuffer
|
||||
raw_database(root, *path)
|
||||
name: TextBuffer
|
||||
append(*name, "ENTITY_PHOTOS_FIXTURE")
|
||||
fixture := PackageRead(TextFromCString(EnvironmentText(*name.bytes[0])), 1048576)
|
||||
check_true("read the 2.1.43 profile", fixture.count > 1000)
|
||||
copy := PackageText(fixture, "\0")
|
||||
descriptor := cast(*TextDescriptor)(*copy)
|
||||
db: *void = null
|
||||
error: *u8 = null
|
||||
check_true("open the 2.1.43 database", FixtureOpen(*path.bytes[0], *db) == 0 && db != null)
|
||||
check_true("write the 2.1.43 profile", FixtureExec(db, descriptor.data, null, null, *error) == 0)
|
||||
unused FixtureClose(db)
|
||||
PackageFree(copy)
|
||||
PackageFree(fixture)
|
||||
}
|
||||
|
||||
#program_export
|
||||
Check :: () -> s32 {
|
||||
guard := support_begin(data_root())
|
||||
if guard != 0 { return guard }
|
||||
walk := FixturePhoto(2600, 11)
|
||||
tea := FixturePhoto(2700, 12)
|
||||
rain := FixturePhoto(2500, 9)
|
||||
lake := FixturePhoto(2900, 14)
|
||||
lake_preview := FixturePhoto(900, 21)
|
||||
orphan := FixturePhoto(2800, 13)
|
||||
walk_hash := Hash(walk)
|
||||
tea_hash := Hash(tea)
|
||||
rain_hash := Hash(rain)
|
||||
lake_hash := Hash(lake)
|
||||
orphan_hash := Hash(orphan)
|
||||
|
||||
// The profile as 2.1.43 left it, with its files.
|
||||
root := make_root("photos-2.1.43")
|
||||
LoadFixture(root)
|
||||
check_true("the 2.1.43 profile opens and upgrades", storage_init(root) != 0)
|
||||
check_int("the upgrade keeps its records", Count("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.*'"), 16)
|
||||
check_int("the upgrade adds the old-copy tables",
|
||||
Count("SELECT COUNT(*) FROM sqlite_master WHERE name IN ('old_copies_deleted','verified_contents')"), 2)
|
||||
FakeLoadFixture()
|
||||
unused AppCopyText(FIXTURE_SYNC_NODE, fake_nodes[0].address[:])
|
||||
unused AppCopyText(FIXTURE_OTHER_NODE, fake_nodes[1].address[:])
|
||||
check_true("the account has two nodes", SyncNodeAdd(FIXTURE_SYNC_NODE) && SyncNodeAdd(FIXTURE_OTHER_NODE))
|
||||
check_true("write walk", DiaryStorePrepare() && PackageWrite(DiaryStorePath(WALK_FILE), walk))
|
||||
check_true("write tea", PackageWrite(DiaryStorePath(TEA_FILE), tea))
|
||||
check_true("write the orphan", PackageWrite(DiaryStorePath(ORPHAN_FILE), orphan))
|
||||
directory := MediaDirectory()
|
||||
check_true("write the library", storage_ensure_dir(directory) != 0 &&
|
||||
PackageWrite(MediaPath(walk_hash, false), walk) && PackageWrite(MediaPath(lake_hash, true), lake_preview))
|
||||
old_records := OldRecords()
|
||||
check_true("the old records read whole", old_records.count > 4000)
|
||||
// The other node cannot delete until the end.
|
||||
fake_nodes[1].no_deletes = true
|
||||
|
||||
// Before anything moves, every photo lists and draws as before.
|
||||
check_int("the library lists walk", MediaQuery("", false), 1)
|
||||
check_int("Trash lists lake", MediaQuery("", true), 1)
|
||||
check_true("Diary draws walk from the library", DiaryPhotoAsset(PackageText("diary:", WALK_FILE)) ==
|
||||
PackageText(PackageText("media/", walk_hash), ".png"))
|
||||
check_true("Diary draws tea from its file", DiaryPhotoAsset(PackageText("diary:", TEA_FILE)) ==
|
||||
PackageText(PackageText("diary/photos/", TEA_FILE), ".png"))
|
||||
|
||||
// A delegate device moves nothing.
|
||||
storage_delegate_mode = FixtureDelegateMode
|
||||
MoveSteps()
|
||||
check_int("a delegate moves nothing", Count("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.*'"), 0)
|
||||
storage_delegate_mode = FixtureOwnerMode
|
||||
|
||||
// The photos whose bytes are here move; nothing old changes.
|
||||
MoveSteps()
|
||||
check_int("walk, tea and rain move", Count("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*'"), 3)
|
||||
check_true("walk keeps its library name and day", EntityField(walk_hash, "name") == "IMG_2041.png" &&
|
||||
EntityField(walk_hash, "day") == "2024-04-02" && EntityField(walk_hash, "added_at") == "1792000100")
|
||||
check_true("tea is named as its entry names it", EntityField(tea_hash, "name") == "Tea cup" &&
|
||||
EntityField(tea_hash, "day") == "2024-04-03")
|
||||
check_true("rain moves from its chunks", EntityField(rain_hash, "size") == "2500" &&
|
||||
PackageRead(MediaPath(rain_hash, false), DIARY_FILE_LIMIT) == rain)
|
||||
check_true("lake waits for its bytes, and the orphan stays", EntityField(lake_hash, "hash") == "" &&
|
||||
EntityField(orphan_hash, "hash") == "")
|
||||
check_true("no old record changes while photos move", OldRecords() == old_records)
|
||||
check_true("the Diary files stay", PackageRead(DiaryStorePath(WALK_FILE), DIARY_FILE_LIMIT) == walk &&
|
||||
PackageRead(DiaryStorePath(TEA_FILE), DIARY_FILE_LIMIT) == tea)
|
||||
check_int("each photo lists once", MediaQuery("", false), 3)
|
||||
check_int("lake still lists in Trash", MediaQuery("", true), 1)
|
||||
// A photo over 8 MiB is two chunks.
|
||||
big := FixturePhoto(9000000, 31)
|
||||
big_hash := Hash(big)
|
||||
check_true("a large photo is added", MediaAddBytes(big, MediaAddition.{.name = "pano.png"}).succeeded)
|
||||
|
||||
// An interrupted pass, then a full other node and an unreachable one:
|
||||
// no old copy goes, and the record names chunks only once a node has
|
||||
// them all.
|
||||
fake_nodes[1].full = true
|
||||
sent := RunPass(1)
|
||||
check_int("the pass is interrupted after one request", sent, 1)
|
||||
check_int("nothing is deleted", fake_deletes, 0)
|
||||
fake_nodes[0].offline = true
|
||||
unused RunPass(1000)
|
||||
check_int("an unreachable sync node gets nothing", Count("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*' AND json_type(value,'$.blobs') IS NOT NULL"), 0)
|
||||
fake_nodes[0].offline = false
|
||||
RunPasses()
|
||||
check_true("lake's old copy came here", PackageRead(MediaPath(lake_hash, false), DIARY_FILE_LIMIT) == lake)
|
||||
check_int("the full node got none", Count(PackageText(PackageText("SELECT COUNT(*) FROM diary_blobs WHERE node='", FIXTURE_OTHER_NODE),
|
||||
"' AND blob NOT IN (SELECT address FROM fixture_node_blobs)")), 0)
|
||||
check_true("the full node is marked full", SyncNodeStorageRead(FIXTURE_OTHER_NODE).full)
|
||||
MoveSteps()
|
||||
check_true("lake moves, in Trash, with its name and preview", EntityField(lake_hash, "name") == "Lake.png" &&
|
||||
EntityField(lake_hash, "trashed") == "1" && EntityField(lake_hash, "preview.hash") == Hash(lake_preview))
|
||||
RunPasses()
|
||||
check_int("every moved photo names its chunks",
|
||||
Count("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*' AND json_array_length(value,'$.blobs')=1"), 4)
|
||||
check_true("the large photo names two chunks of their sealed sizes",
|
||||
EntityField(big_hash, "blobs[0].size") == "8388624" && EntityField(big_hash, "blobs[1].size") == "611408" &&
|
||||
FakeHas(FIXTURE_SYNC_NODE, EntityField(big_hash, "blobs[1].address")))
|
||||
check_true("each chunk is on the sync node", FakeHas(FIXTURE_SYNC_NODE, EntityField(walk_hash, "blobs[0].address")) &&
|
||||
FakeHas(FIXTURE_SYNC_NODE, EntityField(lake_hash, "preview.blobs[0].address")))
|
||||
check_int("still no old copy goes before the node confirms", fake_deletes, 0)
|
||||
MoveSteps()
|
||||
check_true("and no old record changes", OldRecords() == old_records)
|
||||
|
||||
// The node keeps the records; a damaged chunk there holds back walk.
|
||||
GoodSync()
|
||||
walk_chunk := EntityField(walk_hash, "blobs[0].address")
|
||||
damaged := FakeFind(FIXTURE_SYNC_NODE, walk_chunk)
|
||||
good_bytes := PackageText(fake_blobs[damaged].bytes, "")
|
||||
damaged_descriptor := cast(*TextDescriptor)(*fake_blobs[damaged].bytes)
|
||||
damaged_descriptor.data[30] = cast(u8)((cast(s32)damaged_descriptor.data[30] + 1) % 256)
|
||||
RunPasses()
|
||||
MoveSteps()
|
||||
check_true("a photo whose chunk comes back damaged keeps its old records",
|
||||
FieldAt(Setting(PackageText("cell.diary.file.", WALK_FILE)), 0, "photo") < 0 &&
|
||||
FieldAt(Setting(PackageText("cell.media.", walk_hash)), 0, "photo") < 0)
|
||||
check_true("and its Diary file", PathExists(DiaryStorePath(WALK_FILE)))
|
||||
check_true("tea comes back whole and its entry names it",
|
||||
Setting(PackageText("cell.diary.file.", TEA_FILE)) ==
|
||||
PackageText(PackageText(PackageText("{\"hash\":\"", tea_hash), "\",\"size\":2700,\"photo\":\""), PackageText(tea_hash, "\"}")))
|
||||
check_true("tea's Diary file left, its library file stays", !PathExists(DiaryStorePath(TEA_FILE)) &&
|
||||
PackageRead(MediaPath(tea_hash, false), DIARY_FILE_LIMIT) == tea)
|
||||
check_int("rain's chunks shrink", Count(PackageText(PackageText("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.diary.chunk.",
|
||||
rain_hash), ".*' AND value='-'")), 3)
|
||||
check_true("lake's old records name it and keep every field",
|
||||
FieldAt(Setting(PackageText("cell.media.", lake_hash)), 0, "blob") >= 0 &&
|
||||
FieldAt(Setting(PackageText("cell.media.", lake_hash)), 0, "photo") >= 0 &&
|
||||
FieldAt(Setting(PackageText("cell.media.preview.", lake_hash)), 0, "photo") >= 0)
|
||||
fake_blobs[damaged].bytes = good_bytes
|
||||
exec_db_sql("DELETE FROM verified_contents")
|
||||
RunPasses()
|
||||
MoveSteps()
|
||||
check_true("walk, whole now, moves too", FieldAt(Setting(PackageText("cell.diary.file.", WALK_FILE)), 0, "photo") >= 0 &&
|
||||
FieldAt(Setting(PackageText("cell.media.", walk_hash)), 0, "photo") >= 0 && !PathExists(DiaryStorePath(WALK_FILE)))
|
||||
check_true("Diary draws walk from the library without its file",
|
||||
DiaryPhotoAsset(PackageText("diary:", WALK_FILE)).count > 0 && DiaryPhotoAsset(PackageText("diary:", WALK_FILE))[:6] == "media/")
|
||||
check_true("the orphan stays as it was", PathExists(DiaryStorePath(ORPHAN_FILE)) &&
|
||||
FieldAt(Setting(PackageText("cell.diary.file.", ORPHAN_FILE)), 0, "photo") < 0)
|
||||
|
||||
// Old copies go, but not from a node that cannot delete yet.
|
||||
RunPasses()
|
||||
check_true("the sync node deleted walk's, lake's and its preview's old copies",
|
||||
Count("SELECT COUNT(*) FROM old_copies_deleted WHERE node='https://sync.photos.test'") == 3)
|
||||
walk_old := PackageText(read_db_text(PackageText(PackageText("SELECT json_extract(value,'$.blob') FROM settings WHERE key='cell.media.",
|
||||
walk_hash), "'")), "")
|
||||
check_true("the other node keeps walk's old copy for now",
|
||||
Count("SELECT COUNT(*) FROM old_copies_deleted WHERE node='https://other.photos.test'") == 0 &&
|
||||
FakeHas(FIXTURE_OTHER_NODE, walk_old) && !FakeHas(FIXTURE_SYNC_NODE, walk_old))
|
||||
fake_nodes[1].no_deletes = false
|
||||
RunPasses()
|
||||
check_int("then it deletes it", Count("SELECT COUNT(*) FROM old_copies_deleted WHERE node='https://other.photos.test'"), 3)
|
||||
check_true("walk's old copy is gone everywhere", !FakeHas(FIXTURE_OTHER_NODE, walk_old))
|
||||
check_true("the orphan's old copy stays", FakeHas(FIXTURE_SYNC_NODE,
|
||||
read_db_text("SELECT json_extract(value,'$.blob') FROM settings WHERE key='cell.diary.file.photo-20240405000000-1.bin'")))
|
||||
check_int("every photo still lists", MediaQuery("", false), 4)
|
||||
check_int("lake still lists in Trash", MediaQuery("", true), 1)
|
||||
check_true("the full node keeps being asked, and nothing else goes", RunPass(1000) == 1 && fake_puts > 0)
|
||||
fake_nodes[1].full = false
|
||||
RunPasses()
|
||||
check_true("with room it gets every photo", FakeHas(FIXTURE_OTHER_NODE, EntityField(walk_hash, "blobs[0].address")) &&
|
||||
FakeHas(FIXTURE_OTHER_NODE, EntityField(lake_hash, "preview.blobs[0].address")))
|
||||
check_int("then nothing more goes", RunPass(1000), 0)
|
||||
|
||||
// Another app moved a photo first: its record lacks what the old
|
||||
// record knows, which joins it before the old record names it.
|
||||
harbor := FixturePhoto(3300, 41)
|
||||
harbor_hash := Hash(harbor)
|
||||
harbor_old := PackageText(PackageText("{\"hash\":\"", harbor_hash),
|
||||
"\",\"size\":3300,\"type\":\"png\",\"name\":\"Harbor.png\",\"day\":\"2024-06-01\",\"taken\":\"2024-06-01\",\"added\":1792000300,\"capture\":0,\"trashed\":1}")
|
||||
storage_set_setting_text(PackageText("cell.media.", harbor_hash), harbor_old)
|
||||
storage_set_setting_text(EntityPhotoKey(harbor_hash), PackageText(PackageText("{\"hash\":\"", harbor_hash),
|
||||
"\",\"size\":3300,\"type\":\"image/png\",\"taken_at\":1717200000,\"caption\":\"From Photos\"}"))
|
||||
check_true("its bytes are here", PackageWrite(MediaPath(harbor_hash, false), harbor))
|
||||
RunPasses()
|
||||
GoodSync()
|
||||
RunPasses()
|
||||
MoveSteps()
|
||||
check_true("the old record's name, day and Trash join the photo's record",
|
||||
EntityField(harbor_hash, "name") == "Harbor.png" && EntityField(harbor_hash, "day") == "2024-06-01" &&
|
||||
EntityField(harbor_hash, "trashed") == "1" && EntityField(harbor_hash, "added_at") == "1792000300" &&
|
||||
EntityField(harbor_hash, "caption") == "From Photos")
|
||||
check_true("the old record waits until that goes out", FieldAt(Setting(PackageText("cell.media.", harbor_hash)), 0, "photo") < 0)
|
||||
GoodSync()
|
||||
RunPasses()
|
||||
MoveSteps()
|
||||
check_true("then it names the photo", FieldAt(Setting(PackageText("cell.media.", harbor_hash)), 0, "photo") >= 0)
|
||||
PackageFree(harbor_old)
|
||||
|
||||
// The account's other device draws each photo from its entity record.
|
||||
moved: [4]string = .[walk_hash, tea_hash, rain_hash, lake_hash]
|
||||
records: [4]string
|
||||
for index: 0..3 {
|
||||
records[index] = MediaEntityRecord(moved[index])
|
||||
}
|
||||
big_record := MediaEntityRecord(big_hash)
|
||||
storage_close()
|
||||
second := make_root("photos-second-device")
|
||||
check_true("init the other device", storage_init(second) != 0)
|
||||
storage_set_setting_text("sync_private_key", read_fixture_key())
|
||||
storage_set_setting_text("sync_public_id", FIXTURE_ACCOUNT)
|
||||
storage_set_setting_text("sync_server_url", FIXTURE_SYNC_NODE)
|
||||
for index: 0..3 {
|
||||
storage_set_setting_text(EntityPhotoKey(moved[index]), records[index])
|
||||
PackageFree(records[index])
|
||||
}
|
||||
storage_set_setting_text(EntityPhotoKey(big_hash), big_record)
|
||||
PackageFree(big_record)
|
||||
check_int("it has the five photos", MediaQuery("", false) + MediaQuery("", true), 5)
|
||||
RunPasses()
|
||||
check_int("each photo's preview comes, or without one its original", FixturePreviewsHere(moved), 4)
|
||||
check_true("lake's original waits until it is opened", PathExists(MediaPath(lake_hash, true)) &&
|
||||
!PathExists(MediaPath(lake_hash, false)))
|
||||
check_true("the moved photos draw on this device", MediaAsset(walk_hash, false).count > 0 &&
|
||||
MediaAsset(tea_hash, false).count > 0 && MediaAsset(rain_hash, false).count > 0)
|
||||
MediaWant(lake_hash)
|
||||
MediaWant(big_hash)
|
||||
RunPasses()
|
||||
check_true("an original opened here comes", PackageRead(MediaPath(lake_hash, false), DIARY_FILE_LIMIT) == lake)
|
||||
check_true("the large photo comes in its two chunks", PackageRead(MediaPath(big_hash, false), DIARY_FILE_LIMIT) == big)
|
||||
storage_close()
|
||||
PackageFree(old_records)
|
||||
return failures
|
||||
}
|
||||
|
||||
// How many of these photos have their preview, or when they have none their
|
||||
// original, on this device.
|
||||
FixturePreviewsHere :: (hashes: [4]string) -> s32 {
|
||||
here: s32 = 0
|
||||
for hash: hashes {
|
||||
record := MediaEntityRecord(hash)
|
||||
preview := EntityPreviewContent(record)
|
||||
photo := EntityPhotoContent(record)
|
||||
path := MediaPath(hash, preview.valid)
|
||||
content := ifx preview.valid then preview else photo
|
||||
if EntityContentMatches(content, PackageRead(path, DIARY_FILE_LIMIT)) {
|
||||
here += 1
|
||||
}
|
||||
PackageFree(path)
|
||||
PackageFree(record)
|
||||
}
|
||||
return here
|
||||
}
|
||||
|
||||
FixtureDelegateMode :: () -> s32 {
|
||||
return 2
|
||||
}
|
||||
|
||||
FixtureOwnerMode :: () -> s32 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// The fixture account's private key, "42" repeated.
|
||||
read_fixture_key :: () -> string {
|
||||
out: Vec(u8)
|
||||
for index: 0..2559 {
|
||||
unused index
|
||||
BuilderPrint(*out, "42")
|
||||
}
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# A profile Inbe 2.1.43 left upgrades: its photos move to the account's
|
||||
# entity data against nodes the test answers from memory, on a real SQLite
|
||||
# database in this build's own directory.
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
ziran=${1:-"$root/build/ziran-toolchain/bin/ziran"}
|
||||
liboqs=${2:-"$root/vendor-builds/linux/x86_64/inbe-liboqs/lib/liboqs.a"}
|
||||
work=$root/build/entity-photos-zi-test
|
||||
include=$root/build/packages/ziran/include
|
||||
monocypher=$root/build/packages/monocypher/src
|
||||
|
||||
exec 9>"$work.lock"
|
||||
flock 9
|
||||
|
||||
rm -rf "$work"
|
||||
mkdir -p "$work/generated" "$work/data"
|
||||
"$ziran" build --target=c --define PLATFORM_DESKTOP --root "$root/tests" \
|
||||
--module-path "$root/src" \
|
||||
--module-path "$root/build/packages/kryon/src/ui" \
|
||||
--module-path "$root/build/packages/kss/src" $(sh "$root/scripts/package-paths.sh" "$root/build/packages") \
|
||||
--module-path "$root/build/packages/kryon/src/backend" \
|
||||
--module-path "$root/build/packages/game2d/src" \
|
||||
--module-path "$root/build/packages/ziran/std" \
|
||||
--module-path "$root/build/packages/daochi-client" \
|
||||
--entry entity_photos_behavior:Check \
|
||||
-o "$work/generated" "$root/tests/entity_photos_behavior.zi" \
|
||||
"$root/tests/sync_test_host.zi"
|
||||
cat > "$work/generated/main.c" <<'C'
|
||||
#include "entity_photos_behavior.h"
|
||||
#include <stdio.h>
|
||||
/* Files are flushed by the browser's storage only on the web. */
|
||||
void app_web_storage_flush(void) {}
|
||||
int main(void)
|
||||
{
|
||||
int result = Check();
|
||||
if (result != 0) fprintf(stderr, "entity photos check failed with code %d\n", result);
|
||||
return result == 0 ? 0 : 1;
|
||||
}
|
||||
C
|
||||
"${CC:-cc}" -std=c11 -O0 -ffunction-sections -fdata-sections \
|
||||
-I"$include" -I"$work/generated" -I"$root/vendor-builds/sqlite" \
|
||||
-I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$monocypher/monocypher.c" "$liboqs" \
|
||||
-Wl,--gc-sections -ldl -lpthread -lz -lm -o "$work/test"
|
||||
APP_DATA_ROOT=$work/data
|
||||
ENTITY_PHOTOS_FIXTURE=$root/tests/fixtures/photos-2.1.43.sql
|
||||
export APP_DATA_ROOT ENTITY_PHOTOS_FIXTURE
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY "$work/test"
|
||||
rm -rf "$work/data"
|
||||
echo "Photos of a 2.1.43 profile moved to the account's entity data without losing any"
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Print the known-answer entity record of tests/storage_sync_behavior.zi.
|
||||
|
||||
The record is sealed with libsodium (PyNaCl), as other apps of the account
|
||||
seal theirs, in Daochi's record profile (docs/entity-data.md): the record
|
||||
key of kind photos from the test account's private key, XChaCha20-Poly1305
|
||||
with a fixed nonce, and the profile's sorted-key envelope, base64url without
|
||||
padding. Run it to reproduce the constants the test embeds.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
|
||||
import nacl.bindings
|
||||
|
||||
# set_account() stores the private key as the hex digits "42" repeated.
|
||||
PRIVATE_KEY = bytes([0x42]) * 2560
|
||||
ACCOUNT = "7e1d" * 16
|
||||
HASH = "1f2e3d4c5b6a7988" * 4
|
||||
COLLECTION = "private.entity.v1.photos"
|
||||
SCHEMA = "entity.photo.v1"
|
||||
NONCE = bytes(range(24))
|
||||
|
||||
|
||||
def base64url(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
key = hmac.new(PRIVATE_KEY, b"daochi-entity-v1/records/photos", hashlib.sha256).digest()
|
||||
plain = json.dumps({"hash": HASH, "size": 6000, "type": "image/jpeg", "taken_at": 1792224900,
|
||||
"width": 4032, "height": 3024, "added_at": 1792224960,
|
||||
"name": "IMG_2041.jpg", "caption": "Written by another app"},
|
||||
separators=(",", ":"), sort_keys=True)
|
||||
aad = ('{"account_id":"%s","app_id":"entity","collection":"%s","id":"%s","schema":"%s"}'
|
||||
% (ACCOUNT, COLLECTION, HASH, SCHEMA))
|
||||
sealed = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_encrypt(
|
||||
plain.encode(), aad.encode(), NONCE, key)
|
||||
envelope = ('{"aad":%s,"alg":"xchacha20poly1305","ciphertext":"%s","key_id":"entity-v1",'
|
||||
'"nonce":"%s","profile":"daochi-record-v1"}' % (aad, base64url(sealed), base64url(NONCE)))
|
||||
print("record key:", key.hex())
|
||||
print("plain:", plain)
|
||||
print("nonce:", base64url(NONCE))
|
||||
print("ciphertext:", base64url(envelope.encode()))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write tests/fixtures/photos-2.1.43.sql: a profile as Inbe 2.1.43 left it.
|
||||
|
||||
Released versions kept Diary photos as Diary files and the media library in
|
||||
private.inbe.v1.media, each photo's bytes as one old sealed copy at
|
||||
/api/v1/blobs/inbe/ (src/cells/diary_records.zi). The fixture holds that
|
||||
profile's database rows and, in fixture_node_blobs, the old copies its two
|
||||
nodes hold. Its tables are Inbe 1.8.9's (schema-1.8.9.sql) with the
|
||||
sync_record_copies and diary_blobs tables of 2.1.43; the upgrade adds the
|
||||
rest, as it does for any older profile. tests/entity_photos_behavior.zi writes the photos' files from
|
||||
the same byte pattern (FixturePhoto) and upgrades the profile.
|
||||
|
||||
Photos: walk (a Diary photo with an old copy, also in the library), tea (a
|
||||
Diary photo never uploaded), rain (a Diary photo from before copies, kept
|
||||
as hex chunks), lake (a library photo in Trash whose original is only on
|
||||
the node, with a preview here), orphan (a Diary file no entry includes).
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||
|
||||
USER = "fixture-user"
|
||||
ACCOUNT = "7e1d" * 16
|
||||
PRIVATE_KEY_HEX = "42" * 2560
|
||||
SYNC_NODE = "https://sync.photos.test"
|
||||
OTHER_NODE = "https://other.photos.test"
|
||||
CHUNK = 1024
|
||||
|
||||
|
||||
def photo(size: int, seed: int) -> bytes:
|
||||
"""PNG's signature, then (index * 7 + seed) % 251, as FixturePhoto."""
|
||||
header = bytes([137, 80, 78, 71, 13, 10, 26, 10])
|
||||
return bytes(header[index] if index < 8 else (index * 7 + seed) % 251 for index in range(size))
|
||||
|
||||
|
||||
def sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def old_copy(data: bytes) -> tuple[str, str, bytes]:
|
||||
"""A released version's sealed copy: its address, its key and its bytes."""
|
||||
private = bytes.fromhex(PRIVATE_KEY_HEX)
|
||||
master = hmac.new(private, b"inbe-diary-blob-key-v1", hashlib.sha256).digest()
|
||||
key = hmac.new(master, sha(data).encode(), hashlib.sha256).digest()
|
||||
sealed = ChaCha20Poly1305(key).encrypt(bytes(12), data, b"inbe.diary.blob.v1")
|
||||
return sha(sealed), key.hex(), sealed
|
||||
|
||||
|
||||
def quote(text: str) -> str:
|
||||
return "'" + text.replace("'", "''") + "'"
|
||||
|
||||
|
||||
class Fixture:
|
||||
def __init__(self) -> None:
|
||||
self.lines: list[str] = []
|
||||
self.clock = 1792000000
|
||||
|
||||
def setting(self, key: str, value: str) -> None:
|
||||
self.clock += 1
|
||||
self.lines.append(f"INSERT INTO settings VALUES({quote(USER)},{quote(key)},{quote(value)},{self.clock});")
|
||||
|
||||
def document(self, name: str, document: dict) -> None:
|
||||
"""A day's document as hex chunks beside its entry (DiaryRecordSave)."""
|
||||
data = json.dumps(document, separators=(",", ":"), ensure_ascii=False).encode()
|
||||
self.chunks(sha(data), data)
|
||||
count = (len(data) + CHUNK - 1) // CHUNK
|
||||
self.setting(f"cell.diary.file.{name}",
|
||||
json.dumps({"hash": sha(data), "count": count, "size": len(data)}, separators=(",", ":")))
|
||||
|
||||
def chunks(self, digest: str, data: bytes) -> None:
|
||||
for index in range(0, (len(data) + CHUNK - 1) // CHUNK):
|
||||
self.setting(f"cell.diary.chunk.{digest}.{index}", data[index * CHUNK:(index + 1) * CHUNK].hex())
|
||||
|
||||
def node_blob(self, node: str, address: str, sealed: bytes) -> None:
|
||||
self.lines.append(f"INSERT INTO fixture_node_blobs VALUES({quote(node)},{quote(address)},{quote(sealed.hex())});")
|
||||
|
||||
def known(self, node: str, address: str) -> None:
|
||||
self.lines.append(f"INSERT INTO diary_blobs VALUES({quote(node)},{quote(address)});")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
walk = photo(2600, 11)
|
||||
tea = photo(2700, 12)
|
||||
rain = photo(2500, 9)
|
||||
lake = photo(2900, 14)
|
||||
lake_preview = photo(900, 21)
|
||||
orphan = photo(2800, 13)
|
||||
fixture = Fixture()
|
||||
schema = Path(__file__).with_name("schema-1.8.9.sql").read_text()
|
||||
out = [schema.rstrip(),
|
||||
"CREATE TABLE IF NOT EXISTS sync_record_copies( collection TEXT NOT NULL, id TEXT NOT NULL, json TEXT NOT NULL, PRIMARY KEY(collection,id));",
|
||||
"CREATE TABLE IF NOT EXISTS diary_blobs( node TEXT NOT NULL, blob TEXT NOT NULL, PRIMARY KEY(node,blob));",
|
||||
"CREATE TABLE fixture_node_blobs(node TEXT NOT NULL, address TEXT NOT NULL, bytes TEXT NOT NULL);"]
|
||||
fixture.lines.append(f"INSERT INTO users VALUES({quote(USER)},1,'local');")
|
||||
fixture.lines.append(f"INSERT INTO meta VALUES('current_user_id',{quote(USER)});")
|
||||
fixture.setting("sync_private_key", PRIVATE_KEY_HEX)
|
||||
fixture.setting("sync_public_key", "fixture-public-key")
|
||||
fixture.setting("sync_public_id", ACCOUNT)
|
||||
fixture.setting("sync_server_url", SYNC_NODE)
|
||||
fixture.setting("sync_enabled", "1")
|
||||
|
||||
walk_address, walk_key, walk_sealed = old_copy(walk)
|
||||
fixture.setting("cell.diary.file.photo-20240402081500-1.bin", json.dumps(
|
||||
{"hash": sha(walk), "size": len(walk), "blob": walk_address, "key": walk_key}, separators=(",", ":")))
|
||||
fixture.setting("cell.diary.file.photo-20240403090000-1.bin",
|
||||
json.dumps({"hash": sha(tea), "size": len(tea)}, separators=(",", ":")))
|
||||
fixture.chunks(sha(rain), rain)
|
||||
fixture.setting("cell.diary.file.photo-20240301000000-1.bin", json.dumps(
|
||||
{"hash": sha(rain), "count": 3, "size": len(rain)}, separators=(",", ":")))
|
||||
orphan_address, orphan_key, orphan_sealed = old_copy(orphan)
|
||||
fixture.setting("cell.diary.file.photo-20240405000000-1.bin", json.dumps(
|
||||
{"hash": sha(orphan), "size": len(orphan), "blob": orphan_address, "key": orphan_key}, separators=(",", ":")))
|
||||
fixture.document("2024-04-02.json", {"version": 1, "date": "2024-04-02", "text": "Walk",
|
||||
"photos": [{"file": "photo-20240402081500-1.bin", "name": "IMG_2041.png"}]})
|
||||
fixture.document("2024-04-03.json", {"version": 1, "date": "2024-04-03",
|
||||
"text": "Tea\n\n", "photos": []})
|
||||
fixture.document("2024-04-04.json", {"version": 1, "date": "2024-04-04", "text": "Rain",
|
||||
"photos": [{"file": "photo-20240301000000-1.bin", "name": "Rain"}]})
|
||||
|
||||
# The library: walk joined it from the Diary and shares its old copy;
|
||||
# lake was added in Photos and moved to Trash.
|
||||
fixture.setting(f"cell.media.{sha(walk)}", json.dumps(
|
||||
{"hash": sha(walk), "size": len(walk), "type": "png", "name": "IMG_2041.png", "day": "2024-04-02",
|
||||
"taken": "2024-04-02", "added": 1792000100, "capture": 0, "trashed": 0,
|
||||
"blob": walk_address, "key": walk_key}, separators=(",", ":")))
|
||||
lake_address, lake_key, lake_sealed = old_copy(lake)
|
||||
preview_address, preview_key, preview_sealed = old_copy(lake_preview)
|
||||
fixture.setting(f"cell.media.{sha(lake)}", json.dumps(
|
||||
{"hash": sha(lake), "size": len(lake), "type": "png", "name": "Lake.png", "day": "2024-05-01",
|
||||
"taken": "2024-05-01T10:00:00+02:00", "added": 1792000200, "capture": 1, "trashed": 1,
|
||||
"blob": lake_address, "key": lake_key}, separators=(",", ":")))
|
||||
fixture.setting(f"cell.media.preview.{sha(lake)}", json.dumps(
|
||||
{"hash": sha(lake_preview), "size": len(lake_preview), "type": "png",
|
||||
"blob": preview_address, "key": preview_key}, separators=(",", ":")))
|
||||
|
||||
for address, sealed in ((walk_address, walk_sealed), (lake_address, lake_sealed),
|
||||
(preview_address, preview_sealed), (orphan_address, orphan_sealed)):
|
||||
fixture.node_blob(SYNC_NODE, address, sealed)
|
||||
fixture.known(SYNC_NODE, address)
|
||||
fixture.node_blob(OTHER_NODE, walk_address, walk_sealed)
|
||||
fixture.known(OTHER_NODE, walk_address)
|
||||
|
||||
out.extend(fixture.lines)
|
||||
header = ("-- An Inbe 2.1.43 profile with photos, made by make_photos_fixture.py.\n"
|
||||
"-- Do not edit; change the script and run it again.\n")
|
||||
Path(__file__).with_name("photos-2.1.43.sql").write_text(header + "\n".join(out) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
-- An Inbe 2.1.43 profile with photos, made by make_photos_fixture.py.
|
||||
-- Do not edit; change the script and run it again.
|
||||
-- Inbe 1.8.9 schema_create SQL, extracted from src/storage/db.c.
|
||||
-- Upstream commit: 5cdfa63d6ad9989cc1d51af5edb1d067cf453176
|
||||
PRAGMA journal_mode=DELETE;
|
||||
PRAGMA foreign_keys=ON;
|
||||
CREATE TABLE IF NOT EXISTS meta( key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS users( id TEXT PRIMARY KEY, created_at INTEGER NOT NULL, kind TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS settings( user_id TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY(user_id,key));
|
||||
CREATE TABLE IF NOT EXISTS social_snapshots( user_id TEXT NOT NULL, kind TEXT NOT NULL, json TEXT NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY(user_id,kind));
|
||||
CREATE TABLE IF NOT EXISTS sessions( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, started_at INTEGER NOT NULL, local_date INTEGER NOT NULL, topic INTEGER NOT NULL DEFAULT 0, activity INTEGER NOT NULL DEFAULT 0, source TEXT NOT NULL, imported_at INTEGER NOT NULL, rounds_hash INTEGER NOT NULL, deleted_at INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0, UNIQUE(user_id,started_at,rounds_hash));
|
||||
CREATE TABLE IF NOT EXISTS session_rounds( session_id TEXT NOT NULL, round_index INTEGER NOT NULL, seconds INTEGER NOT NULL, PRIMARY KEY(session_id,round_index));
|
||||
CREATE TABLE IF NOT EXISTS meditation_logs( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, session_id TEXT NOT NULL, duration_seconds INTEGER NOT NULL, completed_at INTEGER NOT NULL, updated_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE IF NOT EXISTS habits( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, name TEXT NOT NULL, description TEXT NOT NULL DEFAULT '', color_r INTEGER NOT NULL, color_g INTEGER NOT NULL, color_b INTEGER NOT NULL, sync_mode INTEGER NOT NULL, sync_activity INTEGER NOT NULL, counter_enabled INTEGER NOT NULL DEFAULT 0, sort_order INTEGER NOT NULL, deleted_at INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL DEFAULT 0);
|
||||
CREATE TABLE IF NOT EXISTS habit_days( habit_id TEXT NOT NULL, local_date INTEGER NOT NULL, completed INTEGER NOT NULL, count INTEGER NOT NULL DEFAULT 0, session_count INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL, PRIMARY KEY(habit_id,local_date));
|
||||
CREATE TABLE IF NOT EXISTS imports( id TEXT PRIMARY KEY, imported_at INTEGER NOT NULL, format TEXT NOT NULL, source_name TEXT NOT NULL, session_count INTEGER NOT NULL, habit_count INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS sync_outbox( seq INTEGER PRIMARY KEY AUTOINCREMENT, entity_type TEXT NOT NULL, entity_id TEXT NOT NULL, local_date INTEGER NOT NULL DEFAULT 0, queued_at INTEGER NOT NULL, UNIQUE(entity_type,entity_id,local_date));
|
||||
CREATE TABLE IF NOT EXISTS sync_ops( op_id TEXT PRIMARY KEY, client_id TEXT NOT NULL, seq INTEGER NOT NULL, entity_type TEXT NOT NULL, entity_id TEXT NOT NULL, local_date INTEGER NOT NULL DEFAULT 0, op_type TEXT NOT NULL, payload_json TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, sent_at INTEGER NOT NULL DEFAULT 0, acked_at INTEGER NOT NULL DEFAULT 0);
|
||||
INSERT OR IGNORE INTO meta(key,value) VALUES('schema_version','1');
|
||||
CREATE TABLE IF NOT EXISTS sync_record_copies( collection TEXT NOT NULL, id TEXT NOT NULL, json TEXT NOT NULL, PRIMARY KEY(collection,id));
|
||||
CREATE TABLE IF NOT EXISTS diary_blobs( node TEXT NOT NULL, blob TEXT NOT NULL, PRIMARY KEY(node,blob));
|
||||
CREATE TABLE fixture_node_blobs(node TEXT NOT NULL, address TEXT NOT NULL, bytes TEXT NOT NULL);
|
||||
INSERT INTO users VALUES('fixture-user',1,'local');
|
||||
INSERT INTO meta VALUES('current_user_id','fixture-user');
|
||||
INSERT INTO settings VALUES('fixture-user','sync_private_key','4242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242424242Line truncated
|
||||
INSERT INTO settings VALUES('fixture-user','sync_public_key','fixture-public-key',1792000002);
|
||||
INSERT INTO settings VALUES('fixture-user','sync_public_id','7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d',1792000003);
|
||||
INSERT INTO settings VALUES('fixture-user','sync_server_url','https://sync.photos.test',1792000004);
|
||||
INSERT INTO settings VALUES('fixture-user','sync_enabled','1',1792000005);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.file.photo-20240402081500-1.bin','{"hash":"396f9e353b6d701b4a170676c908fb0af4788e280e191402b713ab628e3330f1","size":2600,"blob":"199f8b35113dd98a171bbe1ce0869034ba9cac3ad7faabd31dc52189bf3b9420","key":"f184c0927349f91f7c94fe209e2707ccd7c36b6dd767e5110288bdbbc5517ced"}',1792000006);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.file.photo-20240403090000-1.bin','{"hash":"d06bbdf4dfe8364e398a85908d9248e95837720781707cc31aeb435983071f50","size":2700}',1792000007);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.chunk.51421669e6af84457128a1b90a649f565c794c7f1b9787e341c6c7ef23f7a7eb.0','89504e470d0a1a0a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e',1792000008);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.chunk.51421669e6af84457128a1b90a649f565c794c7f1b9787e341c6c7ef23f7a7eb.1','959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f',1792000009);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.chunk.51421669e6af84457128a1b90a649f565c794c7f1b9787e341c6c7ef23f7a7eb.2','262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f9050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf400070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef501080f161d242b323940474e555c636a71787f868d949ba2a9b0b7',1792000010);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.file.photo-20240301000000-1.bin','{"hash":"51421669e6af84457128a1b90a649f565c794c7f1b9787e341c6c7ef23f7a7eb","count":3,"size":2500}',1792000011);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.file.photo-20240405000000-1.bin','{"hash":"dbcb529f63b530c70e42520e1eb78b91a9e17f56048281e69ce94ca2ed4bf8e7","size":2800,"blob":"842ae959d4bc0e175c35333cf731e723fc20e5cd66968dc155645515b4ace73e","key":"52b739cfac7fb0f7a3fccb690250ea12e19ac48fe3641a383721a7f23fa71b26"}',1792000012);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.chunk.8aa71613314f4cf34dc36f085f37cc5d80526cce58df8d881c9adac0a07842e6.0','7b2276657273696f6e223a312c2264617465223a22323032342d30342d3032222c2274657874223a2257616c6b222c2270686f746f73223a5b7b2266696c65223a2270686f746f2d32303234303430323038313530302d312e62696e222c226e616d65223a22494d475f323034312e706e67227d5d7d',1792000013);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.file.2024-04-02.json','{"hash":"8aa71613314f4cf34dc36f085f37cc5d80526cce58df8d881c9adac0a07842e6","count":1,"size":118}',1792000014);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.chunk.85667f1b5accad95aece8792ff0ffbc3f387485a5da9efb320d4c6d3689dcd25.0','7b2276657273696f6e223a312c2264617465223a22323032342d30342d3033222c2274657874223a225465615c6e5c6e215b546561206375705d2864696172793a70686f746f2d32303234303430333039303030302d312e62696e29222c2270686f746f73223a5b5d7d',1792000015);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.file.2024-04-03.json','{"hash":"85667f1b5accad95aece8792ff0ffbc3f387485a5da9efb320d4c6d3689dcd25","count":1,"size":106}',1792000016);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.chunk.f163159b413be13acb1c3baa3112b5e61cb998d592e907e50371135294b2dfb4.0','7b2276657273696f6e223a312c2264617465223a22323032342d30342d3034222c2274657874223a225261696e222c2270686f746f73223a5b7b2266696c65223a2270686f746f2d32303234303330313030303030302d312e62696e222c226e616d65223a225261696e227d5d7d',1792000017);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.diary.file.2024-04-04.json','{"hash":"f163159b413be13acb1c3baa3112b5e61cb998d592e907e50371135294b2dfb4","count":1,"size":110}',1792000018);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.media.396f9e353b6d701b4a170676c908fb0af4788e280e191402b713ab628e3330f1','{"hash":"396f9e353b6d701b4a170676c908fb0af4788e280e191402b713ab628e3330f1","size":2600,"type":"png","name":"IMG_2041.png","day":"2024-04-02","taken":"2024-04-02","added":1792000100,"capture":0,"trashed":0,"blob":"199f8b35113dd98a171bbe1ce0869034ba9cac3ad7faabd31dc52189bf3b9420","key":"f184c0927349f91f7c94fe209e2707ccd7c36b6dd767e5110288bdbbc5517ced"}',1792000019);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.media.cfe833065a48380d04fa070a4e62fec866e9207038f7695c1f97c4e410110b1f','{"hash":"cfe833065a48380d04fa070a4e62fec866e9207038f7695c1f97c4e410110b1f","size":2900,"type":"png","name":"Lake.png","day":"2024-05-01","taken":"2024-05-01T10:00:00+02:00","added":1792000200,"capture":1,"trashed":1,"blob":"7ba1b40521f6c91ac444b7e00a59892f7eed946af359753a31f29377d292248e","key":"f84b2fbd79ef10fb77ae3e91bcce44ae532aff07b9bbdfdb7622137d6b30339a"}',1792000020);
|
||||
INSERT INTO settings VALUES('fixture-user','cell.media.preview.cfe833065a48380d04fa070a4e62fec866e9207038f7695c1f97c4e410110b1f','{"hash":"e3b01d1f728cc6711d87059ca54e62548c1f368c70d23c31df269c1e3a61270f","size":900,"type":"png","blob":"906c47e206bd75b351fc809effbfa7e850138351acda397bbba38b28ed8ca392","key":"848904e376fcec32d2008c160d080cc63d3cba354770667e91c56b65c7702fc9"}',1792000021);
|
||||
INSERT INTO fixture_node_blobs VALUES('https://sync.photos.test','199f8b35113dd98a171bbe1ce0869034ba9cac3ad7faabd31dc52189bf3b9420','337bb36681a88151f51f8c62783583c765ce1df2c16913c016c455c0e95d43f7d3c22409e2659adbd2c63c13297a42e0f8659ecf1d09cd1aa68faae24dd2b0979c1dd6c185c3e707e1ec7633c98c4678c2dc30c8a990308751181c3d2690c85d9ea35db97359071a47c5694b51e9cdb5a928cbd37000779c69ab6d1d366a4b35ce17c2719630491456b58aa9b32e5c300068e0fd0d4daf992a19c5b47a216f2963e10a7c308374692100e55e6204da08940dd0c26b159f8c496995e6af3aac5fb651fe52f5e6d2f789557b33e6f0de1e9df30a809939dee87d30d014c3240779679ea1cca6f9568c7a87cc823a3d73a5fd33e68429839bad34a3b976c2f6a13783813d2857d27309584d1e39d845529d3ec5257d2e85f948a072b62c788ed521c379912a14357fa3fe6b9c0ff602b4bf06025f272ebbda87b910706514a91615526a50c04e5c7df351dd1e20f28d5c320d0f4424002edd0537ded2fec9a1dc829e29c5cc6b2a16638d9d49d53afdca20f8f68ec698820fd92fc037a1ab6c04b40436c5b2330772b3edad806eb8cebe86e0722cd6d42b077be838d298befec81c82e3441eaf1c08fd819136f7dc22b10aa90f8b69737915b8d6961ad08aa6050c4a6acc94356e5b02ab692165683af4b64007ae6705f41078f977dd044179e8767a39c2bfafaf7545ae09225980fe689958886baec61fca19525a77306d094170a27bb950b482a6aa05a7a56a22b5e9e05acd288e332fbd226beebfa6d1b39f327b26652c7abcf316fe3447213423bf73c3bcd40dcb782096884a96e15e705993955217f3d3810e3833866de682bab415e6200af4a555761c58edc9c7d1c5cae13cba7afee999d17d0aa9f05d7bdf5fae9ab1f9d87d5d0635bd0f842aab5989427f221de67afb45c83b338a30632bb0fd76ffcbe63fc6d03e38c228ab40f8e4b999c17af5e86f94b9c4cb9da493e8b4c47a994cafc62858d794a0d6950024ed90514f4b3ddec84e1d29853897dbe372f408c1d15b81a2cbf1b084585a6e604d242477265c3970a81a4a0027af5c6b0434746d610a3abfba0d6f41599693887e05b203f8f5f53f7193fc7593e3cceecfa149ccdae96a0d6d1dda10127851d55ffd733fbc4c584d9652a85c34f7ab2f5a4ee13c84db34aedbd73b99263e51951a23d5b464ac182c526dbb338a0d1a347541e4e626933045b98b8e61ad99a7d20aec2f12e5c5e061e09e87ac35b1a54256798ec1be744ce0cd8561ae45e442c0b033a3fad2bad32170c322d3b1c9abd7023858813c5cfc06a8f41b7734d4249b2ffed909e283b0b101bf81e96986cf51419721b67c5cb5efd399caa45b97cd0a2a9a7b35f1b91db0a4bc9429bf9895510b59f68fdf573824756ba664306ee7291506d5338f2165d4578728f52735d47877bde0ece2ff2809c3309e51d1c078c5a61e9dcdd752fb52003063f9bdfd71b282724fe4c331f12212fd88ab86319acbaf5321b2827e8eb375732febc3f1cd165d9c332219c1cac81f8ac4850ee11b74777d563d170d72ee6aeeaa62ff93a75a04e56c8cf8caa2fd5c1920a0fdb5d34f39200643c340bafff6c38539b5928400f0e22055833f76e5de380cb93d8a800a13f9e2f5b2c7eded60dbbd32ddd1fe06dbb369c58d4026336f448c9e3a1f73dfaccfe785606c39a9899159a838c56b514e2e05f74628e8c7772328bcc038443185d7cd40eed15147874e5c2406eb50f2e6bd6f6a2676c27ab675506f06f790f2f283d0038d7bb38aa0d795a02fa2c8ac3da035a309ea424b31b78e98512d7f4c8833d297b74442c73d36d76c62e12c6006e0f8e2ce03cf00886b316636665a5495b2aeabb02140c24ea833a7cd8af39ebba19a9a68c70aa37c1b9d7d8a86fe508dbfad7ef7dac944835ff913f23c83f7010d160d8050a3a7064286930a4c0b04fd72449788ad2d2cb26fa7628665e1b6b6a983dbb1ea7f1cf76ff212673184a64be6ae190126f1cda2e761f17d00d10bbb8a1002165491ad4cf1a2582173cbd07496c8890c5b2a765e12c48445093a02477289a302fc18c9bf2c78c11033e1d92cc9f8805e7ab50c12e76457874b9501845e5bd82795ba0a1c8d189bad3bc2ba30288bf220f3ee83b2fb43f4c2e24bd26b1628e71c4075cdccca637ca7b435b011dcf364cac5cb943870a3bc873114de8ddc696d3e10a5dd47ce3b0d0938c8f3d54e1d451bdbb722a37baebf70bbae21a9b824c83cf9da54b4d2b0401b28c0f38f6c1939103b3e035bef6da88a6860ebfef64ab442e33f7250551927ad9d2921071437758ae6e035b190d7e3bcb9b27b00163ce09545fc121b0da7448f1c9be222d502d4517c35386778ddc1ff34df676e949a20dbd56e5b61acb6a6b9423a47bfde92196e10438481147df53e08a5501864c6da4ae56c6b4ac15b336b3d43d1ff81f9a512f08cbe0478ad276e8052bb0903fd958cac8ad8d4babcddf2ecdd65edd8928e775c188501be32f93362c87533844de00e54e97e0c8b20c212fc527e0b54ee1e509a6c6903a4d92c9aacd9b229790dd0768cc78b8129c73df40e2b15f7fce9ac2f80797e0ec11b2e4c09394099bae8d30e2bdac7a110c3eb109fd45c264f757942a85a9013f736cab1054d727eac63e00d84dfb7b5047ac55a18a000b202f1992604bd7c089a29e734f89c7ea20dc5674f11594128faea3c5e5f1d2ec0503391d4b3d5b389ab2b5999f5bdbbe52c10aa03b3f44bf796fc20bbf387a494105c14fbd64c59b23b06fd1ada6b0cf86499a37e9910e26e1282fe611e16a77219c2108d80527ebab376a8c7a78cfc2c99d6bf86c245741c519155925e93b4926cce07b59501e636921bc7c2663d5f9e43e15ae3ab00f71b3374d562981307d16fe19f94cfa00d8b25f1ed28cf6fec970483593d95a412f818b54b57b8e83ce7f692e59dace43d50d374bd135110a429c10308c52aa18fbca3601fce039917b0bc4ab3d73b44b98c6cd741e634ecccd1badf768b70ecb8e678c48de0d3d6c63e42d9da24e12d54f2aa39bda460bf85a0761a4b938ded9d5a5f958b01e353afd940486fa48d26b2b6ec85f07c1d3c8a4f3b5ad015ad9045ee523f92014c708d9c7355a0c94c4c211c67c58b0950db7b7266fe1694e48702809565d6805f3dd33c87e6c8b06dc596b38d5543f9f0d4a38126486e11a8b6e9af3715ee6fca736b752c14fcb7ba47df5fc6c5f99059af3e7ba3d533b0f712c5cb6b794f2b5736f6dc80e84a8c659bd6593720eeb0c94df8ffb11e481e57897b67513328a15d37c029fbcaa465a8bf24633ce86177a2553d2db9dcb4d49f00a03d07d5d42abdf4c1bccd7e70379bb9fbc567f3502319e9278d400d344a8ef6a8eb961c73bc91d6731722de81b35c08367e0ee7236cd989e520fb87941e97113a6a126f566e58d02bc37a98Line truncated
|
||||
INSERT INTO diary_blobs VALUES('https://sync.photos.test','199f8b35113dd98a171bbe1ce0869034ba9cac3ad7faabd31dc52189bf3b9420');
|
||||
INSERT INTO fixture_node_blobs VALUES('https://sync.photos.test','7ba1b40521f6c91ac444b7e00a59892f7eed946af359753a31f29377d292248e','3da1e7ee0da565f115f88921eb17d0545c835f698f827b79643f9819d5df18b22b5c78062fc77ab762332c1362457da408bd8d075ce24aaf6f90b9726a94d4ce333351f50f7d1c446911a11f8803fe2b7cdca063eeb4c749d4696e6f757fe613f870add493f143a83ef3e1d22e8f5e4e126b88dcbef551c3669f97b041a138c120579b04702695fed11e81aa4458d6de66b2f1d0d7be517423ca95703aee1729ef07c77e4c40aac630771729c343668daa952955e4ff3a08cb55d2a670eef31967ddc78bac7daec3a81f5c610783f9d7a5685f3b5641c8a7c9f9e4094c2c70cbb427e44924899bc79b39247f50d48c8e9c41f3c985bcb0e04caf46a72a9d0239a214936af1a1a5e9f5bd95510b165c020360ce63d7d39eea8e8ea67becbe1daad33d9bf576109e0817eec9ab20ee2daa5d4690552b940ec8787ec48e1bda5321fded400961c877ccde91be4d967fa3158e2886101ca160c67a216a432c998fcd5df1cefcc531f7a2c64fe807626d5ab32f733f3263c53388ade56a0bd81d2aba98f120cc5ff266e68612309fea109449d1a454bd13f370c6bcd1852a24adcaa13d4b6647a96c345b357b455f6ef1ea6acf57714cb64df3d1b5dd9058c790600346c330ac6a9abbe955a9520a0e0b010d4ca1e2208cc396ccd06d9eca14c775956c64606657ee413bee54c4b4f4043ed797b933b3fb638ff8239e264e64df16f293d4867ac08dcd266fcc585661d6ff4a7e715745fe0757d8f1ffc89f09ab51ef2d162875eaeb4954619577f9cca95767d80e9d68701f0534a66e5ec8f7adeabe148e722da5566ab352ed2f76d6f0acb3053113d772c779bb5ecd48ff502e60b8f0f232c188e13f9eec4bebea27f21f36052fb39dcdf9e40861ccba995d2c19e86bba18f766c93301c151a7193a9597f68ffb1112e56cd5d10cbbcceaa09d1b9c3d028de71a9137766315e83dce7af13a2d60687c3cdf81ea920fcdcdcf324f4cec22018405a34d8a2e22630483a7be00cfaf00c574d9884525d65ebe9251d9c8fe3e8092a6fa6e0692b33017ab0a1a034ab484d1121b61f156b526a98341a24bca4cc7db4ae52eac7b06d7ba89fa9129ea38b9a52242946321068b22495b4c678d428e36382fa85b85686d6a93c258bf71e5e1c144c5f93404a3787052223e07cea4026acec345fb198cffd269dcdcf81629d7bbaadd13d014d8be87f6d01934f32cca761fb7dc262bc197e0887eff40c46c1cb53176701e08f351e57d82a6c393b4c61d623b6827b3923bdae6d514c8c7a457de8a5cb8b6a5031be4d8a1c8887c6d5f7a06372f4cee998d6abe84518c1eff4ce8ed9eeff8cd7ce7642397f027f768cfc1f186e4edec768f133b2ab8e92bec0ae7f0d2659b1c6d6ccb739132a1343fcfa7eab2310a79ec7852030607cdd873e017e5a0141c0adc12444f153e769228affa469c9cf83b84685aeddf2e469848e44c8ff6125a787c6e2b4371f770e653295162ad9e96f2448f55c7ac2754d56822093be074a85bac5e73d60758a93dcd93f4ff5cdb8a8bc5df59970cebcecb13899495a0f79d6d3400e50a4d19b9239542c8e68dc91eb531b15b7ca84c0bb6278497ded65d1d3a776f32c8e38633bbb30147aebf7fb9072d52c88e6236d4763c2f929df9f02107142f2f341635936eb8ff3b902c8d8b874ae5e17105cc57ab3abe4e741148bfda0cd8994e74103d65e359c49cecabb4b26a5610a148e95e931f63bdfe025fbf86a5304a1130b15e021f9bca7fc34455f18f5a389ba2d0374f84f36d8c324e47e1126d0c16d57531b0c6459f99be5006596772ad88f4ea609740b6786651050b49915e5ec2b8c5f5ea7fe330857bf6a0583f01f8cb1970e1eca297311044e15051f9663214e727a3dfc1fe58efa77911bf4f375c2e56d3437176f219c523367654604b2223bd48b4c14497ea4c0c5c8bd7a4c25d2b15a87dbb17b0b5decb8482ae30b2bb3a6da38dbefb803dcb901b536bd20f61ae812c5795c2cb6f0c2a488f157ea47568e398bc409083b2d2ba13eee7d58cf3a4e9ba06a654e6ff7c8586cee7980401e49a4a257190d8a1bbad10cc83bbf47cefccafbed4f6ae647a1c0c2d54a9cbe904c801b26b14114e60cfe9dd82370f35f456d80be2fcd62098bf462a79cf4d5b1902fae4d4e45cc54dcfb3a478f91b79d91244e0e01319ba1381fb531be3e904961dd6b68211c84da95aaea3ed603d9f621df75e771930302dcea4669e89618831d6d473b64e25f2eadc02fd1a1112a02088325b5c395816944a3cb4dea6dd4b726ca6fb5e4b5ada4cacf54e4ad5fbe20cfbbe2156ae3e85232c7e67d57b80e32686ca4a33539d4b89f34bda10b41e29b81907cf76fbd01b0e4b133350ed403d655a9d01863dc74fcddfa50274cb48c84cb47c09d35ee5dc8819e0262b65b1bd04f9a4bcac891a61dcefbc1447c4aa6871392be9c040ab361ae55262527d5187f81709c4287d4d4c2ff1c19caba789a5b0c0dd605489fe15659cbb7ca80eb6f2f138b88c0f0461acd4d57125c1fb06d1afd1d3fbba6a64027c13adafe41a043012fa5da74d75f54ea02968ce353d60267081933c72671eed73ff272639f5279b573f0e460c6849acf56ec1bb576dd8e6380b42aa7738c75119226d94a43d5977655bcab2a0ba9a86df44f73eae79144b939eede0cd77ee908e9caebfb8c3a4a4671d7d4373156c822c0b034388c9d1ace50d658252c440d1c81f18a205536fd0b4aff2b1dec237bcc8248076e56c0a32b916b879c8cac1dbf183319f3587b2df03dd8394e71261673b2fe288ba7bd8b9b200ba650d1fc005321d5d2f98c5343ff5c7c3642a685318f5d901fa65d8c5452994e191af53b90fdb04661d7ce4419cbbb40344ce608fd50b938d8476597d12647dd73565563c139fbf642fbf076af842cbe3af053c66ab81dff239938c4da9dcac5134f0e1ea539b27b15e0e85e3a7e9af2b2a59822964c2d7bff0bea63f95b27fff564c4c1a04cd6376ce2488a95053afbbdd7437d55e764721b71816daae54186da9956c855ffb08b55a892441a1ed94d47a6cd2408756fad6d0f28e0c78d15927c1452540c55251e86a310a8f4415f0e328a66ceeb9cec856d6f6b24eba1c59d0d294dab51a76743139cb4b92092e371fbe6fb33b008232ca91b26ef1b6436c331b6cd89513c3fd7ef2314042f3d5886d78618c372ec9474f9b942ffe4c68d36b030795608207d206aefe96e4d46c42c52353c1b219f7f4b9d3c1aab7792e64039ad64d18037c97eb50512b8d6f47746c4e7920307969e2455fd6d18a8852a715338a29053f1d39ae41997939608e78241630580571e9f7548abf7f254167efd3771e50bcf25d22202f7b4aeb785a7ff096c9ab9a6f692497012c4f23f15b12cb1110bcaa409cca3c038917befd064a06a9bfLine truncated
|
||||
INSERT INTO diary_blobs VALUES('https://sync.photos.test','7ba1b40521f6c91ac444b7e00a59892f7eed946af359753a31f29377d292248e');
|
||||
INSERT INTO fixture_node_blobs VALUES('https://sync.photos.test','906c47e206bd75b351fc809effbfa7e850138351acda397bbba38b28ed8ca392','bc39653ddae5e0496c69d7e5a981a362c902a94e7ad0c58d6aac82d70212326eb9c1f14d3d488bf1da6d302e70e192b98b6cc1952a9152a267af29d7c81b781131175e7645fc31ef3d604ee0968bcd37ca2b957af20aa0c6b7575da990187f7d39c479be920934b8633f0df024d1dbf6ae3873d5b9964857133a27c35d75f5d6ad809ae768d6d3a35fce907f50831ea3424cde80fa0c92695bd6d2d04748b00fece878d92c986912f5fbda086a4decd1fa19e92ab8ef818dd3dadd5c0f4d259f148f96f365dcc9401f8137ff66a9e6b0e6959c3f41c1b1c4f2c3a0633c3a74502a00855c5358251803c24d9cef42fcbf481e9f414ea3cdccd4eca5e637b52010f8f390aae36d9acb0a55c18b7e91881a78f97bbcda4bfca972e50bba78d441fd4f93b9ef9179a9d9c4af419e4fbe88de896517d8a62b3d09010e69610beed19a8c79f6c445e6e5d71affd9a59b242247026723f5a22e0c1b1e5f16f35df3eb73a7f0821165be602c92763375c10a13f14f54f27b1f829321d9f89ec4a3887d9a973cf25b9417434f6f63a9e86232831040bcc037aaf7f691f9dfe18a63d58ffc67760c4a505a0b581276fe08c3fc7b31b97d8d543a52040be83d3e45b5ab870387344c1919196bcfc1a9c7ddd3dddad0508c76e4d1a4326acaeb193c94e03c4c1e494c7f88f6a73437be52b8356feed63982ae49bf1c6480e3413606807d0dd542c584d43b4ba36c69087069d882ce7a37df4e9eb54a0e1031456733307e2bdd1ba8cad61e2c52e7942fbd37e2fd96757ff44309b2a95a94fcbc6eb8675d79ba7b29cbd0a0a68c4e0bc25bfac4ad9e48a9460ed93dbf1ec410015d9a30517bf9454ecc4fc91dc4ef3c823bc2d7f1e832df10cc17707fcecff5478f3b3d9024e0999cdd2f3d8f1a5eb60dfd9fdf6e87ad60b6ff994c2b6d72182738fb8b3a8b40b5058ea6a2b17c9a6f491f6c4742a859ea2ad52a9db57bcb4d794bc58652f103c37671394dd63ac6a850497f5594dc9de42a8a1396cb3c681bf1913c63848c2745540bea9dbdeb01363c2fb2d1f4d43c808883f812c5b0c3b7869901f8efa1b81fbaf69069fafade62eca1035c7fb8e8304f2c35ffbc7a0c4241c5b94000b77617242a7194c9e8e0c9f18e713777578adaf8c71f963323d38c98bebd4b0f926072255d327e0e50c3049d03ab257bbfdee31d246d64b777ed9d2ea6eef7a80a47543ada29342615605713810c1b292bff92775a339343ed5f017572e9c26f11cf19de687b4a3d819cbbeba534d06163f156d6bc56');
|
||||
INSERT INTO diary_blobs VALUES('https://sync.photos.test','906c47e206bd75b351fc809effbfa7e850138351acda397bbba38b28ed8ca392');
|
||||
INSERT INTO fixture_node_blobs VALUES('https://sync.photos.test','842ae959d4bc0e175c35333cf731e723fc20e5cd66968dc155645515b4ace73e','884500e85a2e73d1f4f53b55a993f109ee484eec053ab67bc5ff2b829061094cbf091483a0f510915419c2417fc069c04a98186a9859236a2c83fcb88fb36a05beb9241c552c47f1f65a7fccfbc0943758790196b57d5cac8c2c58b04798daa13aacba46e7aaf4e018c2ffde0d9896065b8b11ead24af45bb18f9959bae6d8fe14756b2268163d86d94d694a962cacaf00db35f25c5fa86471da2ecad6be66304fd7bd7729a1774710c20c6a713181abe7acc96cc39b706236fa15f864addbe9d4b463018b348022ee5fc126d89e8306a86d4bf96eae4730324159486f17f466877958db890bb4ae22a69976f2ce065abb1c8453783e4aa4c03f9deddafd6525ab09a9f4c0844d6ffc32f60b61f9b4f0daee002dc1ce1057d75bb7d87cd793a85eb8017de4e4c666a965564c6edb1a33a3d3b83d43b599fb6d5690e3350382ee41185f5d11d31849cb43594a4a2059685686c93b2f8ca09878675f0f4bb93ec6621ac321a36733ab4b2658a3c73a74ceb22f398f851816b3925634e9de4c7f34feabb53afc8631fd113036699f30ab768db9ba815147f486c273d4521837872558d59c9e3876a0ecff40e5073ee201aaefbef6f31279cd29cc58dad16fda7d49b73a4fa8e04f5061b832508f91cb4df6f31763c30901c13c55939da404c4440dbae9ebb8b28f5aab8382df267ebd6dcc7cf4437293a53fe3c3331b70e77ab3ad6d4eb5c2d1cb1974113c2f750ec72dac51675ffd206bb46b5d9d12940c9eb6f07fe25ef9ba4a350e0f7d06defc84648bf7d84c657fec9ce9d8a74a86eafe35c292f01256a7d88cd419cce4e57aa7aaaa3bf4f72a334acbde5eb671ac3c32c1ea1f912ef8b420023f382a2549dcfaf8d09aa353bfccf9bd42a998c1859a6a73db667391a93e8589283519857a6c6f29f23acfef7a666b90e7d00014dfd0be218b38b991f4810d6e90df2c0f188bb8a2f94392aafa4e865782284dc67476b77ecedd24481792ddff06e663b86adfe42801f6b832090d8528c869ae67e62513174556d83ebb40dd071cbbd9aa7141a0dbdda5781bc65425f2216b4971a1871925d24be294542334af39ce97ae94fdc508b1924c4c665f6dbde2920a83a55ee0ff4e42dcfa3cecfbe78a9ed79122c26012eb1dfac1e860fcf6db8086c266dd7c09adc3f0c5f3d50c7cf17788bf0771c9a70e85a1db5a987ba29483414faad58707716c4ef743971565566dbf01e1a188c65b461c3fb4f7b56ca0b47870e8b007717c701057bd772a91d884dab7038304d300492806e78caaa820da60f086a94979a5507b81a52ece7284c9c4b74ebed8fcbc5400b5fb8d854ffff47c5b8b4e6ff079abf66ea3e021bc5ed402c76095ace4b24914b025a032ee88d54b2154eb73379ac28952491bfe4cb5f70bc492dc1f4f1ca6bcda1e5bd6fbf6f90c34e9665945abad0e60a27a58eac188d82a7a014926cc1f02147af360649e04966a8774407ced2dd0c57a51d4c7bf1fcf98b48d988b2c35e16f922073b8b4048f9bad4948e068509c937c25a71d1b4a18fd2b0ff70fc6e2204047360e34598061b0415db2a42a2d96fd1d336da795c76e36cb74916f7602da04f065152a75b3af3faa4f3f4c3de7b3b9037705b9ae35aca0e05d62df6fa23e39bb6775a4bdafb03d38c5977bf6f8569ab8993ca7badb31d09370a5d0cb86697ffaac266a1808ba9cdc9c332123f2bbecd135bf767af3b80888fa2d7a59a99041cb77027661476a2083508479ed21e4679de2a74065efc67864ba4c4c1f0f87787cf284d42e1f9e829a78c45f31bd6494e49d59de674f75ce1af947ab68458aca1d76473e6da3a2ef747da7e132fc5ec05015f361a8556fbee4780eba9bc728948c9fce93f69e783d5201e3404dd45da69c161e64f1a0588bfdbd3325614fe2d036b470ca17180711c0b99c97acf54943dd57957498de5351940f29aaf5b8dd997a44bb8f73e53f3d15ec039924a5ac41996ede3ecd0d788af5ec7067235f056201c9d72b722893ca6cc78d26f1ce5b03f730b5c8b99ba3048d28a6ddd54718f91bbbd96be12a872687a06ec6ed37823804fb5c2594f50cedf716e87ecf14ce88c56551b1ee19002c83716b2fe38ea8c89cb8a0b6cc16c279956d721fac083029af7d5b1c650bebf4d2919a71d8bf657456f11221dca6b12c0f2fe86815ff7a1dcd469cfa91e3e99d3eabd04c6e982d5e319cc054fde9f6fd88353b3147f1864bd67deec04dc6609208f65b00a38f2640d3a6a8a6412af597b66ff78e4f0a9ceab4bfe4668102270c81f21f0f5faab88c94c43bbb70372d10f7a31b732d289153ff50cd722175e62357b9026e3688b7adcafd97b1682be880b6cdb9e562b047b9291361f87f4b03d3a6795bea359b99463884567c6aa19ee1e125993e9d047db5f54e07d14332e653265d14da4ad55347070cb47db20571651f326ab8f780117bc53ddc32d8ac3189eac3e568b701dbd1710dd97040eb7b89dbe2eacf9f5fdb555cc081f2e1e68b2a2082ad321c00daefb9e6131985c1e26da20b30032ba67ca9652d17a8cb06458fc9863d2fbfce88b4204631be602d40d444e27f4e9c1084fa1a6e25d8b1b1649682948880176b5944947fcf1a8c0490a3b08bf6d3067228334023e658c50d35d8f69b2792b283ca5b73ad3c4b81168e1e0258bb5a2322a16365e4801c329ff6ebcc988a2a895c3d47d314de4960a6c5bcbdbdfb1ac6b57581fe739d208b8e8316f058a11c80b196c4b4bfe4e855df6246e4171d354dd3d5329318e2674ddfc5628e06513a57727687233ec6ffa6b859a483cad86ad568779d69e5e36150b01de0f28e0c2fe856e058433689634255123e3df70092f0cc79d1285dbbcf1b50e914e7d528da0bc822f871cea35210c61c2b46a6fd140ce23db188bd6c150b2de2302fb396a34d91087a7e98ad56b43ebdb5e6ff78a53d56bcce317468f8dae1746b22f911fa9bcb31e9af860fa7676d1a52e4fd1cee6b35aacd5683ba8af2d7a5b9e111b687117415fa8a5654ba2e4c22213653131887432380eced4c814ad044cc5bcdd105a5c2bdfad9fc08061f88a76f7dedd747617538d1220359379ea7d7e9312a53e1b4f8f30e2b898b24193c7a5013e7800b57ff530af6c3f12624c1f7f8a7292e64389263fc7d62099a259528af2300944481b166d4f02c859cdbbd635c7b4e50dbc8d705acba02a9fa1d116eee7d6a9708a13237fd16c844c897796b55e19488f3ad3a17113a48602d7bc4323907fe3302cd83a421001107a9b958cb17624d2ef9fe0b57922e7d899f07cc79a0cb77d1dd158bc651c8edb4d84cc53b73bea6ed24ec0ee5df060cc0f44a82499ada23dceb33783d224a7c41a08397443f082ddd220d8331ea1bf08590685d6dc911d7d42a5719264abb2e7e3618dfde15d00288515ad0Line truncated
|
||||
INSERT INTO diary_blobs VALUES('https://sync.photos.test','842ae959d4bc0e175c35333cf731e723fc20e5cd66968dc155645515b4ace73e');
|
||||
INSERT INTO fixture_node_blobs VALUES('https://other.photos.test','199f8b35113dd98a171bbe1ce0869034ba9cac3ad7faabd31dc52189bf3b9420','337bb36681a88151f51f8c62783583c765ce1df2c16913c016c455c0e95d43f7d3c22409e2659adbd2c63c13297a42e0f8659ecf1d09cd1aa68faae24dd2b0979c1dd6c185c3e707e1ec7633c98c4678c2dc30c8a990308751181c3d2690c85d9ea35db97359071a47c5694b51e9cdb5a928cbd37000779c69ab6d1d366a4b35ce17c2719630491456b58aa9b32e5c300068e0fd0d4daf992a19c5b47a216f2963e10a7c308374692100e55e6204da08940dd0c26b159f8c496995e6af3aac5fb651fe52f5e6d2f789557b33e6f0de1e9df30a809939dee87d30d014c3240779679ea1cca6f9568c7a87cc823a3d73a5fd33e68429839bad34a3b976c2f6a13783813d2857d27309584d1e39d845529d3ec5257d2e85f948a072b62c788ed521c379912a14357fa3fe6b9c0ff602b4bf06025f272ebbda87b910706514a91615526a50c04e5c7df351dd1e20f28d5c320d0f4424002edd0537ded2fec9a1dc829e29c5cc6b2a16638d9d49d53afdca20f8f68ec698820fd92fc037a1ab6c04b40436c5b2330772b3edad806eb8cebe86e0722cd6d42b077be838d298befec81c82e3441eaf1c08fd819136f7dc22b10aa90f8b69737915b8d6961ad08aa6050c4a6acc94356e5b02ab692165683af4b64007ae6705f41078f977dd044179e8767a39c2bfafaf7545ae09225980fe689958886baec61fca19525a77306d094170a27bb950b482a6aa05a7a56a22b5e9e05acd288e332fbd226beebfa6d1b39f327b26652c7abcf316fe3447213423bf73c3bcd40dcb782096884a96e15e705993955217f3d3810e3833866de682bab415e6200af4a555761c58edc9c7d1c5cae13cba7afee999d17d0aa9f05d7bdf5fae9ab1f9d87d5d0635bd0f842aab5989427f221de67afb45c83b338a30632bb0fd76ffcbe63fc6d03e38c228ab40f8e4b999c17af5e86f94b9c4cb9da493e8b4c47a994cafc62858d794a0d6950024ed90514f4b3ddec84e1d29853897dbe372f408c1d15b81a2cbf1b084585a6e604d242477265c3970a81a4a0027af5c6b0434746d610a3abfba0d6f41599693887e05b203f8f5f53f7193fc7593e3cceecfa149ccdae96a0d6d1dda10127851d55ffd733fbc4c584d9652a85c34f7ab2f5a4ee13c84db34aedbd73b99263e51951a23d5b464ac182c526dbb338a0d1a347541e4e626933045b98b8e61ad99a7d20aec2f12e5c5e061e09e87ac35b1a54256798ec1be744ce0cd8561ae45e442c0b033a3fad2bad32170c322d3b1c9abd7023858813c5cfc06a8f41b7734d4249b2ffed909e283b0b101bf81e96986cf51419721b67c5cb5efd399caa45b97cd0a2a9a7b35f1b91db0a4bc9429bf9895510b59f68fdf573824756ba664306ee7291506d5338f2165d4578728f52735d47877bde0ece2ff2809c3309e51d1c078c5a61e9dcdd752fb52003063f9bdfd71b282724fe4c331f12212fd88ab86319acbaf5321b2827e8eb375732febc3f1cd165d9c332219c1cac81f8ac4850ee11b74777d563d170d72ee6aeeaa62ff93a75a04e56c8cf8caa2fd5c1920a0fdb5d34f39200643c340bafff6c38539b5928400f0e22055833f76e5de380cb93d8a800a13f9e2f5b2c7eded60dbbd32ddd1fe06dbb369c58d4026336f448c9e3a1f73dfaccfe785606c39a9899159a838c56b514e2e05f74628e8c7772328bcc038443185d7cd40eed15147874e5c2406eb50f2e6bd6f6a2676c27ab675506f06f790f2f283d0038d7bb38aa0d795a02fa2c8ac3da035a309ea424b31b78e98512d7f4c8833d297b74442c73d36d76c62e12c6006e0f8e2ce03cf00886b316636665a5495b2aeabb02140c24ea833a7cd8af39ebba19a9a68c70aa37c1b9d7d8a86fe508dbfad7ef7dac944835ff913f23c83f7010d160d8050a3a7064286930a4c0b04fd72449788ad2d2cb26fa7628665e1b6b6a983dbb1ea7f1cf76ff212673184a64be6ae190126f1cda2e761f17d00d10bbb8a1002165491ad4cf1a2582173cbd07496c8890c5b2a765e12c48445093a02477289a302fc18c9bf2c78c11033e1d92cc9f8805e7ab50c12e76457874b9501845e5bd82795ba0a1c8d189bad3bc2ba30288bf220f3ee83b2fb43f4c2e24bd26b1628e71c4075cdccca637ca7b435b011dcf364cac5cb943870a3bc873114de8ddc696d3e10a5dd47ce3b0d0938c8f3d54e1d451bdbb722a37baebf70bbae21a9b824c83cf9da54b4d2b0401b28c0f38f6c1939103b3e035bef6da88a6860ebfef64ab442e33f7250551927ad9d2921071437758ae6e035b190d7e3bcb9b27b00163ce09545fc121b0da7448f1c9be222d502d4517c35386778ddc1ff34df676e949a20dbd56e5b61acb6a6b9423a47bfde92196e10438481147df53e08a5501864c6da4ae56c6b4ac15b336b3d43d1ff81f9a512f08cbe0478ad276e8052bb0903fd958cac8ad8d4babcddf2ecdd65edd8928e775c188501be32f93362c87533844de00e54e97e0c8b20c212fc527e0b54ee1e509a6c6903a4d92c9aacd9b229790dd0768cc78b8129c73df40e2b15f7fce9ac2f80797e0ec11b2e4c09394099bae8d30e2bdac7a110c3eb109fd45c264f757942a85a9013f736cab1054d727eac63e00d84dfb7b5047ac55a18a000b202f1992604bd7c089a29e734f89c7ea20dc5674f11594128faea3c5e5f1d2ec0503391d4b3d5b389ab2b5999f5bdbbe52c10aa03b3f44bf796fc20bbf387a494105c14fbd64c59b23b06fd1ada6b0cf86499a37e9910e26e1282fe611e16a77219c2108d80527ebab376a8c7a78cfc2c99d6bf86c245741c519155925e93b4926cce07b59501e636921bc7c2663d5f9e43e15ae3ab00f71b3374d562981307d16fe19f94cfa00d8b25f1ed28cf6fec970483593d95a412f818b54b57b8e83ce7f692e59dace43d50d374bd135110a429c10308c52aa18fbca3601fce039917b0bc4ab3d73b44b98c6cd741e634ecccd1badf768b70ecb8e678c48de0d3d6c63e42d9da24e12d54f2aa39bda460bf85a0761a4b938ded9d5a5f958b01e353afd940486fa48d26b2b6ec85f07c1d3c8a4f3b5ad015ad9045ee523f92014c708d9c7355a0c94c4c211c67c58b0950db7b7266fe1694e48702809565d6805f3dd33c87e6c8b06dc596b38d5543f9f0d4a38126486e11a8b6e9af3715ee6fca736b752c14fcb7ba47df5fc6c5f99059af3e7ba3d533b0f712c5cb6b794f2b5736f6dc80e84a8c659bd6593720eeb0c94df8ffb11e481e57897b67513328a15d37c029fbcaa465a8bf24633ce86177a2553d2db9dcb4d49f00a03d07d5d42abdf4c1bccd7e70379bb9fbc567f3502319e9278d400d344a8ef6a8eb961c73bc91d6731722de81b35c08367e0ee7236cd989e520fb87941e97113a6a126f566e58d02bc37a9Line truncated
|
||||
INSERT INTO diary_blobs VALUES('https://other.photos.test','199f8b35113dd98a171bbe1ce0869034ba9cac3ad7faabd31dc52189bf3b9420');
|
||||
@@ -152,8 +152,109 @@ Webp :: (date: string) -> string {
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
// A file of `format` whose header names a width and height, as the size
|
||||
// reader finds them; webp is lossy (VP8), lossless (VP8L) or extended (VP8X).
|
||||
Sized :: (format: string, width: s64, height: s64) -> string {
|
||||
out: Vec(u8)
|
||||
if format == "png" {
|
||||
Byte(*out, 137)
|
||||
Chars(*out, "PNG")
|
||||
Byte(*out, 13)
|
||||
Byte(*out, 10)
|
||||
Byte(*out, 26)
|
||||
Byte(*out, 10)
|
||||
Long(*out, 13, false)
|
||||
Chars(*out, "IHDR")
|
||||
Long(*out, width, false)
|
||||
Long(*out, height, false)
|
||||
Byte(*out, 8)
|
||||
} else if format == "gif" {
|
||||
Chars(*out, "GIF89a")
|
||||
Word(*out, width, true)
|
||||
Word(*out, height, true)
|
||||
Byte(*out, 0)
|
||||
} else if format == "jpg" {
|
||||
Byte(*out, 255)
|
||||
Byte(*out, 216)
|
||||
// A comment segment before the frame is skipped.
|
||||
Byte(*out, 255)
|
||||
Byte(*out, 254)
|
||||
Word(*out, 4, false)
|
||||
Chars(*out, "hi")
|
||||
Byte(*out, 255)
|
||||
Byte(*out, 192)
|
||||
Word(*out, 11, false)
|
||||
Byte(*out, 8)
|
||||
Word(*out, height, false)
|
||||
Word(*out, width, false)
|
||||
Byte(*out, 1)
|
||||
Chars(*out, "abc")
|
||||
} else {
|
||||
Chars(*out, "RIFF")
|
||||
Long(*out, 30, true)
|
||||
Chars(*out, "WEBP")
|
||||
Chars(*out, format)
|
||||
Long(*out, 10, true)
|
||||
if format == "VP8 " {
|
||||
Chars(*out, "abc")
|
||||
Byte(*out, 157)
|
||||
Byte(*out, 1)
|
||||
Byte(*out, 42)
|
||||
Word(*out, width, true)
|
||||
Word(*out, height, true)
|
||||
} else if format == "VP8L" {
|
||||
Byte(*out, 47)
|
||||
Long(*out, (width - 1) | ((height - 1) << 14), true)
|
||||
Chars(*out, "abcde")
|
||||
} else {
|
||||
Long(*out, 0, true)
|
||||
Byte(*out, (width - 1) & 255)
|
||||
Word(*out, (width - 1) >> 8, true)
|
||||
Byte(*out, (height - 1) & 255)
|
||||
Word(*out, (height - 1) >> 8, true)
|
||||
}
|
||||
}
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
// The JPEG with a frame of this size before its end.
|
||||
Framed :: (jpeg: string, width: s64, height: s64) -> string {
|
||||
out: Vec(u8)
|
||||
Chars(*out, jpeg[:jpeg.count - 2])
|
||||
Byte(*out, 255)
|
||||
Byte(*out, 192)
|
||||
Word(*out, 11, false)
|
||||
Byte(*out, 8)
|
||||
Word(*out, height, false)
|
||||
Word(*out, width, false)
|
||||
Byte(*out, 1)
|
||||
Chars(*out, "abc")
|
||||
Byte(*out, 255)
|
||||
Byte(*out, 217)
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
SizeIs :: (data: string, format: string, width: s64, height: s64) -> bool {
|
||||
size := MediaSizeOf(data, format)
|
||||
return size.valid && size.width == width && size.height == height
|
||||
}
|
||||
|
||||
#program_export
|
||||
Answer :: () -> s32 {
|
||||
// Sizes come from headers alone; a photo on its side reads upright.
|
||||
if !SizeIs(Sized("png", 4032, 3024), "png", 4032, 3024) { return 20 }
|
||||
if !SizeIs(Sized("gif", 320, 200), "gif", 320, 200) { return 21 }
|
||||
if !SizeIs(Sized("jpg", 600, 400), "jpg", 600, 400) { return 22 }
|
||||
if !SizeIs(Sized("VP8 ", 640, 480), "webp", 640, 480) { return 23 }
|
||||
if !SizeIs(Sized("VP8L", 1000, 700), "webp", 1000, 700) { return 24 }
|
||||
if !SizeIs(Sized("VP8X", 5000, 3000), "webp", 5000, 3000) { return 25 }
|
||||
if MediaSizeOf(Jpeg("2024:06:15 08:30:05", "", 6), "jpg").valid { return 26 }
|
||||
if !SizeIs(Framed(Jpeg("2024:06:15 08:30:05", "", 6), 600, 400), "jpg", 400, 600) { return 29 }
|
||||
sized := Sized("png", 10, 20)
|
||||
for length: cast(s64)0..sized.count - 2 {
|
||||
if MediaSizeOf(sized[:length], "png").valid { return 27 }
|
||||
}
|
||||
if MediaSizeOf(Sized("png", 0, 20), "png").valid || MediaSizeOf(sized, "jpg").valid { return 28 }
|
||||
capture := MediaCaptureOf(Jpeg("2024:06:15 08:30:05", "-03:00"), "jpg")
|
||||
if !capture.valid || capture.year != 2024 || capture.month != 6 || capture.day != 15 ||
|
||||
capture.hour != 8 || capture.minute != 30 || capture.second != 5 { return 1 }
|
||||
|
||||
@@ -37,4 +37,4 @@ env -u DISPLAY -u WAYLAND_DISPLAY ASAN_OPTIONS=detect_leaks=0 "$work/test"
|
||||
--entry media_metadata_behavior:Answer -o "$work/check.zx" \
|
||||
"$root/tests/media_metadata_behavior.zi"
|
||||
test "$("$bin/ziran" run "$work/check.zx")" = 42
|
||||
printf '%s\n' 'Media metadata: Exif capture times and orientations passed natively and in the VM'
|
||||
printf '%s\n' 'Media metadata: Exif capture times, orientations and picture sizes passed natively and in the VM'
|
||||
@@ -1,6 +1,8 @@
|
||||
// The account's media library on a real database: a photo is kept once by
|
||||
// its hash with its capture day and a JPEG preview, Trash keeps it, queries
|
||||
// list it by day or all newest first, and only this account's photos draw.
|
||||
// its hash as a record of the account's entity data, with its capture day
|
||||
// and a JPEG preview, Trash keeps it, queries list it by day or all newest
|
||||
// first, a released version's library record lists until its photo moves,
|
||||
// and only this account's photos draw.
|
||||
#import "byte_text_linux"
|
||||
#import "vec"
|
||||
#import "text"
|
||||
@@ -15,6 +17,8 @@
|
||||
#import, file "../src/storage/storage_core.zi";
|
||||
#import, file "../src/storage/storage_settings.zi";
|
||||
#import, file "../src/storage/media_records.zi";
|
||||
#import, file "../src/storage/entity_records.zi";
|
||||
#import, file "../src/cells/entity_photos.zi";
|
||||
#import, file "../src/cells/package_files.zi";
|
||||
#import, file "../src/cells/diary_records.zi";
|
||||
#import, file "../src/cells/media_store.zi";
|
||||
@@ -103,7 +107,7 @@ Hash :: (data: string) -> string {
|
||||
}
|
||||
|
||||
RecordField :: (hash: string, field: string, output: []u8) -> string {
|
||||
key := PackageText(MEDIA_RECORD_PREFIX, hash)
|
||||
key := EntityPhotoKey(hash)
|
||||
record := MediaRecordRead(key)
|
||||
count := ReadStringText(record, FieldAt(record, 0, field), output)
|
||||
PackageFree(key)
|
||||
@@ -146,11 +150,18 @@ Check :: () -> s32 {
|
||||
check_true("its capture time is the camera's",
|
||||
RecordField(morning_hash, "taken", field[:]) == "2026-10-17T08:15:00")
|
||||
check_true("its name is the file's", RecordField(morning_hash, "name", field[:]) == "IMG_2041.jpg")
|
||||
check_true("its type is read from its bytes", RecordField(morning_hash, "type", field[:]) == "jpg")
|
||||
check_true("its type is read from its bytes", RecordField(morning_hash, "type", field[:]) == "image/jpeg")
|
||||
item := MediaRead(morning_hash)
|
||||
check_true("the record reads back", item.valid && item.size == morning.count && !item.trashed)
|
||||
check_int("the photo and its preview queue to sync",
|
||||
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='media_record'"), 2)
|
||||
check_true("the record reads back", item.valid && item.entity && item.size == morning.count && !item.trashed)
|
||||
check_int("one record of the account's entity data queues to sync",
|
||||
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='entity_record'"), 1)
|
||||
check_int("nothing goes to the released versions' library",
|
||||
read_db_count("SELECT COUNT(*) FROM settings WHERE key GLOB 'cell.media.*'"), 0)
|
||||
check_int("its capture time is in seconds, read as UTC without an offset",
|
||||
read_db_count(PackageText(PackageText("SELECT json_extract(value,'$.taken_at') FROM settings WHERE key='entity.photos.",
|
||||
morning_hash), "'")), 1792224900)
|
||||
check_int("it names no chunks before a node has them",
|
||||
read_db_count("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.photos.*' AND json_type(value,'$.blobs') IS NOT NULL"), 0)
|
||||
|
||||
// The preview: an upright JPEG at most 512 pixels on its longer side.
|
||||
preview_path := MediaPath(morning_hash, true)
|
||||
@@ -168,11 +179,11 @@ Check :: () -> s32 {
|
||||
preview_width := cast(s32)preview[sof + 7] * 256 + cast(s32)preview[sof + 8]
|
||||
check_int("the preview is upright and 512 tall", preview_height, 512)
|
||||
check_int("the preview is 341 wide", preview_width, 341)
|
||||
preview_key := PackageText(MEDIA_PREVIEW_PREFIX, morning_hash)
|
||||
preview_record := MediaRecordRead(preview_key)
|
||||
check_true("the preview's record names its bytes",
|
||||
DiaryMediaMatches(DiaryMediaParse(preview_record), preview))
|
||||
PackageFree(preview_record)
|
||||
photo_record := MediaEntityRecord(morning_hash)
|
||||
preview_content := EntityPreviewContent(photo_record)
|
||||
check_true("the photo's record names its preview's bytes",
|
||||
EntityContentMatches(preview_content, preview) && TextUntilNul(preview_content.format[:]) == "jpg")
|
||||
PackageFree(photo_record)
|
||||
|
||||
// Assets: the preview draws; asking for the original finds it here.
|
||||
preview_asset := PackageText(MediaAsset(morning_hash, false), "")
|
||||
@@ -203,11 +214,11 @@ Check :: () -> s32 {
|
||||
check_true("opening it asks for the original", MediaOriginalWanted(morning_hash))
|
||||
|
||||
// The same bytes again add nothing; the file comes back.
|
||||
queued := read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='media_record'")
|
||||
queued := read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='entity_record'")
|
||||
again := MediaImportBytes(morning, "copy of IMG_2041.jpg")
|
||||
check_true("the same photo is added once", again.succeeded && again.existed)
|
||||
check_int("nothing new is queued",
|
||||
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='media_record'"), queued)
|
||||
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='entity_record'"), queued)
|
||||
check_true("its name stays", RecordField(morning_hash, "name", field[:]) == "IMG_2041.jpg")
|
||||
check_true("the file is back", PackageRead(original_path, DIARY_FILE_LIMIT) == morning)
|
||||
|
||||
@@ -241,15 +252,51 @@ Check :: () -> s32 {
|
||||
!MediaRead(evening_hash).trashed)
|
||||
check_true("rename a photo", MediaSetName(earlier_hash, "Lake \"walk\"\n.jpg"))
|
||||
check_true("the name is one line", RecordField(earlier_hash, "name", field[:]) == "Lake \"walk\" .jpg")
|
||||
// A sealed copy's name keeps every other field.
|
||||
key := PackageText(MEDIA_RECORD_PREFIX, earlier_hash)
|
||||
// Fields another app added stay when this one changes the record.
|
||||
key := EntityPhotoKey(earlier_hash)
|
||||
record := MediaRecordRead(key)
|
||||
copy_blob := "abababababababababababababababababababababababababababababababab"
|
||||
copy_key := "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
|
||||
check_true("name the sealed copy", MediaRecordSetCopy(key, record, copy_blob, copy_key))
|
||||
check_true("the copy is named", RecordField(earlier_hash, "blob", field[:]) == copy_blob &&
|
||||
DiaryMediaUploaded(DiaryMediaParse(MediaRecordRead(key))))
|
||||
check_true("the other fields stay", RecordField(earlier_hash, "day", field[:]) == "2026-10-15")
|
||||
tagged := MediaRecordWith(record, "caption", "\"By the lake\"")
|
||||
check_true("another app adds a field", MediaRecordWrite(key, tagged))
|
||||
check_true("trash it with the field", MediaSetTrashed(earlier_hash, true) && MediaSetTrashed(earlier_hash, false))
|
||||
check_true("the other app's field stays", RecordField(earlier_hash, "caption", field[:]) == "By the lake" &&
|
||||
RecordField(earlier_hash, "day", field[:]) == "2026-10-15")
|
||||
check_int("Trash is true or false in the shared record",
|
||||
read_db_count(PackageText(PackageText("SELECT json_type(value,'$.trashed')='false' FROM settings WHERE key='entity.photos.",
|
||||
earlier_hash), "'")), 1)
|
||||
|
||||
// A released version's library record lists its photo until the photo
|
||||
// moves; its entity record then keeps its name, day, Trash and the time
|
||||
// it was added, and the old record stays for released versions.
|
||||
older := Photo("2026:10:12 09:00:00", 1, 50000, 6)
|
||||
older_hash := Hash(older)
|
||||
older_key := PackageText(MEDIA_RECORD_PREFIX, older_hash)
|
||||
older_out: Vec(u8)
|
||||
BuilderPrint(*older_out, "{\"hash\":\"%\",\"size\":%,\"type\":\"jpg\",\"name\":\"Old walk.jpg\",", older_hash, older.count)
|
||||
BuilderPrint(*older_out, "\"day\":\"2026-10-12\",\"taken\":\"2026-10-12T09:00:00\",\"added\":1792000000,")
|
||||
BuilderPrint(*older_out, "\"capture\":1,\"trashed\":1,\"blob\":\"%\",\"key\":\"%\"}",
|
||||
"abababababababababababababababababababababababababababababababab",
|
||||
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd")
|
||||
older_record := BuilderFinish(older_out)
|
||||
check_true("a released version's record arrives", MediaRecordWrite(older_key, older_record))
|
||||
older_item := MediaRead(older_hash)
|
||||
check_true("its photo lists from it", older_item.valid && !older_item.entity && older_item.trashed &&
|
||||
TextUntilNul(older_item.day[:]) == "2026-10-12")
|
||||
check_int("Trash lists it", MediaQuery("", true), 1)
|
||||
older_path := MediaPath(older_hash, false)
|
||||
check_true("its bytes arrive", PackageWrite(older_path, older))
|
||||
moved := MediaAddBytes(older, MediaAddition.{.source = older_path})
|
||||
check_true("the photo moves", moved.succeeded && moved.existed && MediaRead(older_hash).entity)
|
||||
check_true("its name and day stay", RecordField(older_hash, "name", field[:]) == "Old walk.jpg" &&
|
||||
RecordField(older_hash, "day", field[:]) == "2026-10-12" &&
|
||||
RecordField(older_hash, "taken", field[:]) == "2026-10-12T09:00:00")
|
||||
check_true("it stays in Trash", MediaRead(older_hash).trashed)
|
||||
check_int("the time it was added stays",
|
||||
read_db_count(PackageText(PackageText("SELECT json_extract(value,'$.added_at') FROM settings WHERE key='entity.photos.",
|
||||
older_hash), "'")), 1792000000)
|
||||
check_true("the old record stays as it was", MediaRecordRead(older_key) == older_record)
|
||||
check_int("Trash lists the photo once", MediaQuery("", true), 1)
|
||||
check_true("restore it", MediaSetTrashed(older_hash, false))
|
||||
check_true("the old record is not touched", MediaRecordRead(older_key) == older_record)
|
||||
|
||||
// Files that are not photos are refused.
|
||||
check_true("text is no photo", !MediaImportBytes("just some text", "notes.txt").succeeded)
|
||||
|
||||
+14
-3
@@ -143,7 +143,7 @@ def jpeg(image, quality=88):
|
||||
|
||||
|
||||
def seed_photo(db, user, folder, color, day, taken, name, size):
|
||||
"""A photo and its preview, as the media library stores them."""
|
||||
"""A photo and its preview, as released versions' media library stores them."""
|
||||
image = Image.new("RGB", size, color)
|
||||
ImageDraw.Draw(image).ellipse((size[0] // 4, size[1] // 4, size[0] // 2, size[1] // 2),
|
||||
fill=tuple(min(255, c + 30) for c in color))
|
||||
@@ -187,6 +187,8 @@ with tempfile.TemporaryDirectory(prefix="inbe-photos-") as directory:
|
||||
]
|
||||
# A synced preview whose original has not reached this device yet.
|
||||
(folder / photos[2]).unlink()
|
||||
seeded_records = dict(db.execute("SELECT key,value FROM settings WHERE user_id=? AND key GLOB 'cell.media.*'",
|
||||
(user,)))
|
||||
# A camera's portrait photo: stored 1200 by 800, Exif orientation 6.
|
||||
picked = profile / PICKED_NAME
|
||||
sideways = Image.new("RGB", (1200, 800), PICKED)
|
||||
@@ -225,8 +227,11 @@ with tempfile.TemporaryDirectory(prefix="inbe-photos-") as directory:
|
||||
with sqlite3.connect(profile / "inbe.db", timeout=3) as db:
|
||||
stored = dict(db.execute("SELECT key,value FROM settings WHERE user_id=?", (user,)))
|
||||
assert stored.get("app_used_photos") == "1", stored.get("app_used_photos")
|
||||
item = json.loads(stored[f"cell.media.{digest}"])
|
||||
assert item["name"] == PICKED_NAME and item["type"] == "jpg", item
|
||||
# The added photo is a record of the account's entity data.
|
||||
item = json.loads(stored[f"entity.photos.{digest}"])
|
||||
assert item["name"] == PICKED_NAME and item["type"] == "image/jpeg", item
|
||||
assert item["preview"]["size"] == (folder / (digest + ".preview")).stat().st_size, item
|
||||
assert f"cell.media.{digest}" not in stored, "a released version's record was written"
|
||||
assert (folder / digest).read_bytes() == picked.read_bytes(), "the original is not kept as picked"
|
||||
with Image.open(folder / (digest + ".preview")) as preview:
|
||||
assert preview.format == "JPEG" and preview.size == (341, 512), preview.size
|
||||
@@ -268,6 +273,12 @@ with tempfile.TemporaryDirectory(prefix="inbe-photos-") as directory:
|
||||
assert "frame rejected" not in log and app.poll() is None, log
|
||||
finally:
|
||||
stop(app)
|
||||
# The seeded photos may move to the entity data while the app runs, but
|
||||
# released versions' records stay exactly as they were: nothing here
|
||||
# confirms a move, so nothing old changes.
|
||||
with sqlite3.connect(profile / "inbe.db") as db:
|
||||
records = dict(db.execute("SELECT key,value FROM settings WHERE user_id=? AND key GLOB 'cell.media.*'", (user,)))
|
||||
assert records == seeded_records, "a released version's record changed"
|
||||
|
||||
# A saved Photos pin must survive restart and draw in either dock layout.
|
||||
with sqlite3.connect(profile / "inbe.db") as db:
|
||||
|
||||
@@ -32,7 +32,8 @@ C
|
||||
-I"$root/build/packages/ziran/include" -I"$work/generated" \
|
||||
-I"$root/vendor-builds/sqlite" \
|
||||
-I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$liboqs" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" \
|
||||
"$root/build/packages/monocypher/src/monocypher.c" "$liboqs" \
|
||||
-Wl,--gc-sections -ldl -lpthread -lz -lm -o "$work/test"
|
||||
APP_DATA_ROOT=/tmp/inbe-storage-delegate-zi-test/data \
|
||||
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS \
|
||||
|
||||
@@ -35,7 +35,8 @@ C
|
||||
"${CC:-cc}" -std=c11 -O0 -ffunction-sections -fdata-sections \
|
||||
-I"$include" -I"$work/generated" -I"$root/vendor-builds/sqlite" \
|
||||
-I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$liboqs" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" \
|
||||
"$root/build/packages/monocypher/src/monocypher.c" "$liboqs" \
|
||||
-Wl,--gc-sections -ldl -lpthread -lz -lm -o "$work/test"
|
||||
# Storage must never open the real data directory.
|
||||
APP_DATA_ROOT=/tmp/inbe-storage-more-zi-test/data
|
||||
|
||||
@@ -44,6 +44,9 @@
|
||||
#import, file "../src/storage/sync_nodes.zi";
|
||||
#import, file "../src/storage/sync_node_storage.zi";
|
||||
#import, file "../src/storage/media_records.zi";
|
||||
#import, file "../src/storage/entity_records.zi";
|
||||
#import, file "../src/storage/entity_record_crypto.zi";
|
||||
#import "daochi_client/entity"
|
||||
#import, file "../src/storage/media_node_session.zi";
|
||||
#import, file "../src/storage/sync_session.zi";
|
||||
#import "auth"
|
||||
@@ -2174,6 +2177,143 @@ test_media_records_sync_between_devices :: () {
|
||||
storage_close()
|
||||
}
|
||||
|
||||
// The record of tests/entity_record_vector.py, sealed with libsodium as
|
||||
// other apps of the account seal theirs.
|
||||
ENTITY_VECTOR_ACCOUNT :: "7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d"
|
||||
ENTITY_VECTOR_KEY :: "c47a6fab7d9d756295c797df5b56e10bed452cf4c1c646d262080f5d99ee9869"
|
||||
ENTITY_VECTOR_PLAIN :: "{\"added_at\":1792224960,\"caption\":\"Written by another app\",\"hash\":\"1f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a7988\",\"height\":3024,\"name\":\"IMG_2041.jpg\",\"size\":6000,\"taken_at\":1792224900,\"type\":\"image/jpeg\",\"width\":4032}"
|
||||
ENTITY_VECTOR_NONCE :: "AAECAwQFBgcICQoLDA0ODxAREhMUFRYX"
|
||||
ENTITY_VECTOR_CIPHERTEXT :: "eyJhYWQiOnsiYWNjb3VudF9pZCI6IjdlMWQ3ZTFkN2UxZDdlMWQ3ZTFkN2UxZDdlMWQ3ZTFkN2UxZDdlMWQ3ZTFkN2UxZDdlMWQ3ZTFkN2UxZDdlMWQiLCJhcHBfaWQiOiJlbnRpdHkiLCJjb2xsZWN0aW9uIjoicHJpdmF0ZS5lbnRpdHkudjEucGhvdG9zIiwiaWQiOiIxZjJlM2Q0YzViNmE3OTg4MWYyZTNkNGM1YjZhNzk4ODFmMmUzZDRjNWI2YTc5ODgxZjJlM2Q0YzViNmE3OTg4Iiwic2NoZW1hIjoiZW50aXR5LnBob3RvLnYxIn0sImFsZyI6InhjaGFjaGEyMHBvbHkxMzA1IiwiY2lwaGVydGV4dCI6IlhsYkVDTTRCc09wRXpLc1gyV3JPYnlMMG1rb3htSGVXMmdVdS1IRXFkQ2xrWk4tZ2sxdmJsZHgxbmlNTU80RDFvVjBtVWNZLVRTei1oZ0xnUGF1RXVIcGdpX1lxMDVOT1pzcWJ4c19NWTR6ZHhIMEpJZDExN1pDZmZhQkw2V1RyaElJSzU5NkVMT21JUDJQTEhxdEMyelZobGJFRVM4ZE4xQTdNY1dvNXNJalVyTW9oWXFfQnp4aktZUFhlZGs1ZnRydFdyY0FvOWVUVU5wZEpYZk5CVHdtdUZCbEV3cXhNSGdrdkk4OU0xZlg3SWJ4VTJJUkJYV0JTNFBaNm1iWUdvUWZPZmxZM3RLMFU4MEduQXYzRWZoS0RUcjI5YzQwS3drbVhRanduN0RWTkduZXltOFd1RlhqR0pTTV96NGI2SzFsMWNHLVQwc0Q1WmRvIiwia2V5X2lkIjoiZW50aXR5LXYxIiwibm9uY2UiOiJBQUVDQXdRRkJnY0lDUW9MREEwT0R4QVJFaE1VRlJZWCIsInByb2ZpbGUiOiJkYW9jaGktcmVjb3JkLXYxIn0"
|
||||
|
||||
// One encrypted record of a sync reply.
|
||||
entity_reply_record :: (collection: string, id: string, nonce: string, ciphertext: string) -> string {
|
||||
out: Vec(u8)
|
||||
BuilderPrint(*out, "[{\"collection\":\"%\",\"id\":\"%\",\"key_id\":\"entity-v1\",", collection, id)
|
||||
BuilderPrint(*out, "\"nonce\":\"%\",\"ciphertext\":\"%\",\"updated_at\":\"2030-03-17T17:46:40Z\"}]", nonce, ciphertext)
|
||||
return BuilderFinish(out)
|
||||
}
|
||||
|
||||
// Photos of the account's entity data sync as private.entity.v1.photos in
|
||||
// Daochi's record profile, so every app of the account reads them: libsodium
|
||||
// seals the same bytes as this version, both ways. A record of another kind,
|
||||
// or one that does not open, changes nothing and never stops a sync.
|
||||
test_entity_records_sync_between_devices :: () {
|
||||
first := make_root("sync-entity-a")
|
||||
second := make_root("sync-entity-b")
|
||||
check_true("init entity device a", storage_init(first) != 0)
|
||||
set_account()
|
||||
storage_set_setting_text("sync_public_id", ENTITY_VECTOR_ACCOUNT)
|
||||
key: [32]u8
|
||||
check_true("the account has its photos' record key",
|
||||
storage_private_collection_key(EntityPhotosCollection, ENTITY_RECORD_KEY_ID, *key[0]) != 0)
|
||||
key_hex: [65]u8
|
||||
unused BytesToHex(*key[0], 32, *key_hex[0], 65)
|
||||
check_true("it is the key every app derives", TextFromCString(*key_hex[0]) == ENTITY_VECTOR_KEY)
|
||||
check_true("no other key opens photos",
|
||||
storage_private_collection_key(EntityPhotosCollection, STORAGE_SYNC_RECORD_KEY_ID, *key[0]) == 0)
|
||||
metadata := EntityRecordMetadata.{.account_id = ENTITY_VECTOR_ACCOUNT, .collection = EntityPhotosCollection,
|
||||
.id = MediaTestHash(), .schema = ENTITY_PHOTO_SCHEMA}
|
||||
plain := ENTITY_VECTOR_PLAIN
|
||||
plain_bytes := cast(*TextDescriptor)(*plain)
|
||||
nonce_bytes: [24]u8
|
||||
for index: cast(s32)0..23 {
|
||||
nonce_bytes[index] = cast(u8)index
|
||||
}
|
||||
ciphertext: Vec(u8)
|
||||
nonce: Vec(u8)
|
||||
unused storage_private_collection_key(EntityPhotosCollection, ENTITY_RECORD_KEY_ID, *key[0])
|
||||
check_true("seal the vector's record", EntitySealRecordWith(*key[0], metadata,
|
||||
BytesFromPointer(plain_bytes.data, cast(u64)plain.count), nonce_bytes[:], *ciphertext, *nonce))
|
||||
check_true("the envelope is libsodium's, byte for byte",
|
||||
TextFromBytes(VecSlice(ciphertext, 0, ciphertext.count)) == ENTITY_VECTOR_CIPHERTEXT &&
|
||||
TextFromBytes(VecSlice(nonce, 0, nonce.count)) == ENTITY_VECTOR_NONCE)
|
||||
VecFree(ciphertext)
|
||||
VecFree(nonce)
|
||||
SecureWipe(*key[0], 32)
|
||||
opened: *u8 = null
|
||||
check_true("libsodium's record opens", storage_open_entity_record(EntityPhotosCollection, MediaTestHash(),
|
||||
ENTITY_RECORD_KEY_ID, ENTITY_VECTOR_NONCE, ENTITY_VECTOR_CIPHERTEXT, *opened) != 0 &&
|
||||
TextFromCString(opened) == ENTITY_VECTOR_PLAIN)
|
||||
sqlite_free(cast(*void)opened)
|
||||
check_true("a record of another photo does not open", storage_open_entity_record(EntityPhotosCollection,
|
||||
"2f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a7988", ENTITY_RECORD_KEY_ID,
|
||||
ENTITY_VECTOR_NONCE, ENTITY_VECTOR_CIPHERTEXT, *opened) == 0)
|
||||
check_true("a record of another kind does not open", storage_open_entity_record("private.entity.v1.levels",
|
||||
MediaTestHash(), ENTITY_RECORD_KEY_ID, ENTITY_VECTOR_NONCE, ENTITY_VECTOR_CIPHERTEXT, *opened) == 0)
|
||||
storage_set_setting_text("sync_public_id", "8e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d7e1d")
|
||||
check_true("another account's record does not open", storage_open_entity_record(EntityPhotosCollection,
|
||||
MediaTestHash(), ENTITY_RECORD_KEY_ID, ENTITY_VECTOR_NONCE, ENTITY_VECTOR_CIPHERTEXT, *opened) == 0)
|
||||
storage_set_setting_text("sync_public_id", ENTITY_VECTOR_ACCOUNT)
|
||||
|
||||
// This device's photo goes out sealed, named by its hash alone.
|
||||
item_key := PackageText(ENTITY_PHOTO_PREFIX, MediaTestHash())
|
||||
item := "{\"hash\":\"1f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a7988\",\"size\":6000,\"type\":\"image/jpeg\",\"taken_at\":1792224900,\"added_at\":1792224960,\"name\":\"IMG_2041.jpg\",\"trashed\":false,\"day\":\"2026-10-17\",\"taken\":\"2026-10-17T08:15:00\",\"capture\":true}"
|
||||
storage_set_setting_text(item_key, item)
|
||||
check_int("the photo queues once",
|
||||
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='entity_record'"), 1)
|
||||
check_true("entity payload builds", build_payload())
|
||||
check_true("it goes to the entity data", contains(payload(), "\"collection\":\"private.entity.v1.photos\"") &&
|
||||
contains(payload(), "\"key_id\":\"entity-v1\""))
|
||||
check_true("its record ID is its hash", contains(payload(), "\"id\":\"1f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a7988\""))
|
||||
check_true("its name never leaves the device", !contains(payload(), "IMG_2041") && !contains(payload(), "entity.photos."))
|
||||
check_true("nothing goes to an app's collection", !contains(payload(), "private.inbe.v1.media") &&
|
||||
!contains(payload(), "private.inbe.v1.cells"))
|
||||
copy: TextBuffer
|
||||
append(*copy, records_array())
|
||||
storage_enqueue_all_sync_state()
|
||||
check_int("a backfill queues the photo again",
|
||||
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='entity_record'"), 1)
|
||||
storage_close()
|
||||
|
||||
check_true("init entity device b", storage_init(second) != 0)
|
||||
set_account()
|
||||
storage_set_setting_text("sync_public_id", ENTITY_VECTOR_ACCOUNT)
|
||||
check_true("device b applies a's photo",
|
||||
storage_apply_sync_response_json(response_with(4, TextFromCString(*copy.bytes[0]))) != 0)
|
||||
check_true("b has a's photo", storage_get_setting_text(item_key) == item)
|
||||
check_int("b does not send a's photo back",
|
||||
read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='entity_record'"), 0)
|
||||
// Another app's record of the same photo: its new field joins, and the
|
||||
// fields only this device knows stay.
|
||||
other_app := entity_reply_record(EntityPhotosCollection, MediaTestHash(), ENTITY_VECTOR_NONCE, ENTITY_VECTOR_CIPHERTEXT)
|
||||
check_true("another app's record applies", storage_apply_sync_response_json(response_with(5, other_app)) != 0)
|
||||
check_true("its field joins", read_db_text(PackageText(PackageText("SELECT json_extract(value,'$.caption') FROM settings WHERE key='",
|
||||
item_key), "'")) == "Written by another app")
|
||||
check_true("this device's fields stay", read_db_text(PackageText(PackageText("SELECT json_extract(value,'$.day') FROM settings WHERE key='",
|
||||
item_key), "'")) == "2026-10-17")
|
||||
// Records this version cannot use leave everything as it was.
|
||||
before := PackageText(storage_get_setting_text(item_key), "")
|
||||
unreadable: [4]string = .[
|
||||
entity_reply_record(EntityPhotosCollection, "2f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a79881f2e3d4c5b6a7988",
|
||||
ENTITY_VECTOR_NONCE, ENTITY_VECTOR_CIPHERTEXT),
|
||||
entity_reply_record("private.entity.v1.levels", "0123456789abcdef0123456789abcdef", ENTITY_VECTOR_NONCE,
|
||||
ENTITY_VECTOR_CIPHERTEXT),
|
||||
entity_reply_record(EntityPhotosCollection, MediaTestHash(), "AAECAwQFBgcICQoLDA0ODxAREhMUFRYY",
|
||||
ENTITY_VECTOR_CIPHERTEXT),
|
||||
entity_reply_record(EntityPhotosCollection, MediaTestHash(), ENTITY_VECTOR_NONCE, "e30")
|
||||
]
|
||||
for reply: unreadable {
|
||||
check_true("an entity record this version cannot use doesn't stop the sync",
|
||||
storage_apply_sync_response_json(response_with(6, reply)) != 0)
|
||||
}
|
||||
check_true("they change nothing", storage_get_setting_text(item_key) == before)
|
||||
check_int("they store nothing", read_db_count("SELECT COUNT(*) FROM settings WHERE key GLOB 'entity.*'"), 1)
|
||||
// A change b has not sent yet stays when an earlier record arrives, and
|
||||
// goes out over it with every field.
|
||||
trashed := PackageText(read_db_text(PackageText(PackageText("SELECT json_set(value,'$.trashed',json('true')) FROM settings WHERE key='",
|
||||
item_key), "'")), "")
|
||||
storage_set_setting_text(item_key, trashed)
|
||||
check_int("b's change queues", read_db_count("SELECT COUNT(*) FROM sync_outbox WHERE entity_type='entity_record'"), 1)
|
||||
check_true("an earlier record applies", storage_apply_sync_response_json(response_with(7, TextFromCString(*copy.bytes[0]))) != 0)
|
||||
check_true("b's Trash stays", read_db_count(PackageText(PackageText("SELECT json_extract(value,'$.trashed') FROM settings WHERE key='",
|
||||
item_key), "'")) == 1)
|
||||
check_true("b's change goes out", build_payload() && contains(payload(), MediaTestHash()))
|
||||
PackageFree(before)
|
||||
PackageFree(trashed)
|
||||
PackageFree(item_key)
|
||||
storage_close()
|
||||
}
|
||||
|
||||
// Each node has its own media session on this device, apart from the
|
||||
// sync's; removing a node forgets it and which copies the node holds.
|
||||
test_node_media_sessions :: () {
|
||||
@@ -2329,6 +2469,7 @@ Check :: () -> s32 {
|
||||
test_nested_app_records_sync_between_devices()
|
||||
test_app_order_syncs_between_devices()
|
||||
test_media_records_sync_between_devices()
|
||||
test_entity_records_sync_between_devices()
|
||||
test_node_media_sessions()
|
||||
test_shop_rewards_stay_private()
|
||||
return failures
|
||||
|
||||
@@ -52,10 +52,12 @@ int main(void)
|
||||
return result == 0 ? 0 : 1;
|
||||
}
|
||||
C
|
||||
# Entity records use Monocypher's XChaCha20-Poly1305, as the app does.
|
||||
monocypher=$root/build/packages/monocypher/src
|
||||
"${CC:-cc}" -std=c11 -O0 -ffunction-sections -fdata-sections \
|
||||
-I"$include" -I"$work/generated" -I"$root/vendor-builds/sqlite" \
|
||||
-I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$liboqs" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$monocypher/monocypher.c" "$liboqs" \
|
||||
-Wl,--wrap=sqlite3_prepare_v2 -Wl,--gc-sections -ldl -lpthread -lz -lm -o "$work/test"
|
||||
# Storage must never open the real data directory.
|
||||
APP_DATA_ROOT=/tmp/inbe-storage-sync-zi-test/data
|
||||
|
||||
@@ -35,7 +35,8 @@ C
|
||||
"${CC:-cc}" -std=c11 -O0 -ffunction-sections -fdata-sections \
|
||||
-I"$include" -I"$work/generated" -I"$root/vendor-builds/sqlite" \
|
||||
-I"$root/vendor-builds/linux/x86_64/inbe-liboqs/include" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" "$liboqs" \
|
||||
"$work/generated"/*.c "$root/vendor-builds/sqlite/sqlite3.c" \
|
||||
"$root/build/packages/monocypher/src/monocypher.c" "$liboqs" \
|
||||
-Wl,--gc-sections -ldl -lpthread -lm -o "$work/test"
|
||||
# Storage must never open the real data directory.
|
||||
APP_DATA_ROOT=/tmp/inbe-sync-account-zi-test/data
|
||||
|
||||
+167
-65
@@ -36,6 +36,12 @@
|
||||
#import, file "../src/cells/diary_blobs_native.zi";
|
||||
#import, file "../src/cells/diary_blobs.zi";
|
||||
#import, file "../src/cells/media_store.zi";
|
||||
#import, file "../src/cells/media_diary_photos.zi";
|
||||
#import, file "../src/cells/entity_photos.zi";
|
||||
#import, file "../src/storage/entity_records.zi";
|
||||
#import, file "../src/storage/sync_record_crypto.zi";
|
||||
#import "crypto"
|
||||
#import "json_scan"
|
||||
#import, file "../src/storage/sync_nodes.zi";
|
||||
#import, file "../src/storage/sync_node_storage.zi";
|
||||
#import, file "../src/storage/media_node_session.zi";
|
||||
@@ -169,77 +175,175 @@ synchronize :: (url: string) {
|
||||
check_true("sync drained the queued changes", false)
|
||||
}
|
||||
|
||||
// A Diary photo travels as one sealed copy, which the node keeps at the
|
||||
// photo's size plus 16 bytes, and arrives whole on the account's other
|
||||
// device.
|
||||
expect_photo_copy :: (url: string, a: string, b: string) {
|
||||
open_client(a)
|
||||
png: [6000]u8
|
||||
for index: cast(s32)0..cast(s32)5999 {
|
||||
png[index] = cast(u8)((index * 13 + 7) % 251)
|
||||
}
|
||||
header: [8]u8 = .[cast(u8)137, cast(u8)80, cast(u8)78, cast(u8)71, cast(u8)13, cast(u8)10, cast(u8)26, cast(u8)10]
|
||||
for index: cast(s32)0..7 {
|
||||
png[index] = header[index]
|
||||
}
|
||||
image := TextFromBytes(png[:])
|
||||
source: TextBuffer
|
||||
append(*source, data_root())
|
||||
append(*source, "/photo-source.png")
|
||||
source_path := TextFromCString(*source.bytes[0])
|
||||
unused RemoveFile(source_path)
|
||||
file := OpenExclusivePrivate(source_path)
|
||||
written := file.valid && WriteTextAt(file, image, 0) == image.count
|
||||
check_true("write the photo to attach", CloseFile(file) && written)
|
||||
name := DiaryStoreAttach(source_path)
|
||||
check_true("attach the photo", name.count > 0)
|
||||
DiaryStoreClose()
|
||||
synchronize(url)
|
||||
DiaryBlobsSendNative(url)
|
||||
media := DiaryMediaRead(name)
|
||||
check_true("the photo's copy is on the node", DiaryMediaUploaded(media))
|
||||
synchronize(url)
|
||||
blob_path: TextBuffer
|
||||
append(*blob_path, data_root())
|
||||
append(*blob_path, "/server.db.blobs/")
|
||||
append(*blob_path, storage_get_setting_text("sync_public_id"))
|
||||
append(*blob_path, "/inbe/")
|
||||
append(*blob_path, TextFromBytes(media.blob[:64]))
|
||||
check_int("the node keeps the photo's size plus 16 bytes",
|
||||
cast(s32)PackageFileSize(TextFromCString(*blob_path.bytes[0])), 6016)
|
||||
open_client(b)
|
||||
synchronize(url)
|
||||
check_true("the photo waits on the second device", !DiaryStoreRead(name).succeeded)
|
||||
DiaryStoreClose()
|
||||
DiaryBlobsSendNative(url)
|
||||
check_true("the photo arrives whole on the second device", DiaryStoreRead(name).data == image)
|
||||
DiaryStoreClose()
|
||||
PackageFree(name)
|
||||
}
|
||||
|
||||
// The node's file for a sealed copy, under the server's data directory.
|
||||
server_blob_size :: (server: string, blob: string) -> s32 {
|
||||
// The node's file for a blob of `app` under the server's data directory.
|
||||
server_app_blob_size :: (server: string, app: string, blob: string) -> s32 {
|
||||
path: TextBuffer
|
||||
append(*path, data_root())
|
||||
append(*path, server)
|
||||
append(*path, "server.db.blobs/")
|
||||
append(*path, storage_get_setting_text("sync_public_id"))
|
||||
append(*path, "/inbe/")
|
||||
append(*path, "/")
|
||||
append(*path, app)
|
||||
append(*path, "/")
|
||||
append(*path, blob)
|
||||
return cast(s32)PackageFileSize(TextFromCString(*path.bytes[0]))
|
||||
}
|
||||
|
||||
library_record_blob :: (key: string, output: []u8) -> string {
|
||||
record := MediaRecordRead(key)
|
||||
media := DiaryMediaParse(record)
|
||||
// The node's file for a sealed chunk of the account's entity data.
|
||||
server_blob_size :: (server: string, blob: string) -> s32 {
|
||||
return server_app_blob_size(server, "entity", blob)
|
||||
}
|
||||
|
||||
// The address of the photo's chunk, or of its preview's.
|
||||
library_record_blob :: (hash: string, preview: bool, output: []u8) -> string {
|
||||
record := MediaEntityRecord(hash)
|
||||
content := ifx preview then EntityPreviewContent(record) else EntityPhotoContent(record)
|
||||
PackageFree(record)
|
||||
unused AppCopyText(TextFromBytes(media.blob[:64]), output)
|
||||
if !DiaryMediaUploaded(media) {
|
||||
output[0] = cast(u8)0
|
||||
output[0] = cast(u8)0
|
||||
if content.chunk_count == 1 {
|
||||
unused AppCopyText(TextUntilNul(content.chunks[0].address[:]), output)
|
||||
}
|
||||
return TextUntilNul(output)
|
||||
}
|
||||
|
||||
// A photo's bytes: PNG's signature, then a pattern of `seed`.
|
||||
server_photo :: (bytes: []u8, seed: s32) -> string {
|
||||
header: [8]u8 = .[cast(u8)137, cast(u8)80, cast(u8)78, cast(u8)71, cast(u8)13, cast(u8)10, cast(u8)26, cast(u8)10]
|
||||
for index: cast(s32)0..cast(s32)bytes.count - 1 {
|
||||
bytes[index] = ifx index < 8 then header[index] else cast(u8)((index * 13 + seed) % 251)
|
||||
}
|
||||
return TextFromBytes(bytes)
|
||||
}
|
||||
|
||||
server_photo_file :: (name: string, image: string) -> string {
|
||||
source: TextBuffer
|
||||
append(*source, data_root())
|
||||
append(*source, "/")
|
||||
append(*source, name)
|
||||
path := PackageText(TextFromCString(*source.bytes[0]), "")
|
||||
unused RemoveFile(path)
|
||||
file := OpenExclusivePrivate(path)
|
||||
written := file.valid && WriteTextAt(file, image, 0) == image.count
|
||||
check_true("write the photo to add", CloseFile(file) && written)
|
||||
return path
|
||||
}
|
||||
|
||||
server_move_steps :: () {
|
||||
MediaDiaryPhotosDue()
|
||||
for step: 0..80 {
|
||||
unused step
|
||||
unused MediaDiaryPhotosStep()
|
||||
}
|
||||
}
|
||||
|
||||
// A photo travels as the account's entity data: its record in the
|
||||
// account's own signed sync, its bytes as one sealed chunk, which the node
|
||||
// keeps at the photo's size plus 16 bytes. The account's other device gets
|
||||
// the record in its normal sync and opens the photo whole.
|
||||
expect_photo_copy :: (url: string, a: string, b: string) {
|
||||
open_client(a)
|
||||
png: [6000]u8
|
||||
image := server_photo(png[:], 7)
|
||||
source_path := server_photo_file("photo-source.png", image)
|
||||
added := MediaImportFile(source_path)
|
||||
check_true("add the photo", added.succeeded)
|
||||
hash := PackageText(TextFromBytes(added.hash[:64]), "")
|
||||
synchronize(url)
|
||||
DiaryBlobsSendNative(url)
|
||||
record := MediaEntityRecord(hash)
|
||||
content := EntityPhotoContent(record)
|
||||
PackageFree(record)
|
||||
check_true("the photo's chunk is on the node", content.chunk_count == 1)
|
||||
synchronize(url)
|
||||
check_int("the node keeps the photo's size plus 16 bytes",
|
||||
server_blob_size("/", TextUntilNul(content.chunks[0].address[:])), 6016)
|
||||
open_client(b)
|
||||
synchronize(url)
|
||||
item := MediaRead(hash)
|
||||
check_true("the other device has the photo's record from its sync", item.valid && item.entity)
|
||||
check_true("its original waits there", PackageFileSize(MediaPath(hash, false)) != image.count)
|
||||
MediaWant(hash)
|
||||
DiaryBlobsSendNative(url)
|
||||
check_true("the photo arrives whole on the other device",
|
||||
PackageRead(MediaPath(hash, false), DIARY_FILE_LIMIT) == image)
|
||||
PackageFree(hash)
|
||||
PackageFree(source_path)
|
||||
}
|
||||
|
||||
// A photo a released version kept as an old copy at /api/v1/blobs/inbe/
|
||||
// moves on a real node: its old copy comes to this device, its chunks go
|
||||
// to the node, the node confirms them, they come back whole, and only then
|
||||
// does the node delete the old copy.
|
||||
expect_old_copy_moves :: (url: string, a: string) {
|
||||
open_client(a)
|
||||
png: [7000]u8
|
||||
image := server_photo(png[:], 29)
|
||||
descriptor := cast(*TextDescriptor)(*image)
|
||||
hash_bytes: [65]u8
|
||||
storage_sha256_hex(descriptor.data, image.count, *hash_bytes[0])
|
||||
hash := PackageText(TextFromCString(*hash_bytes[0]), "")
|
||||
// Sealed as released versions sealed it.
|
||||
master: [32]u8
|
||||
check_true("the account key makes old copies",
|
||||
storage_private_record_key_for_context("inbe-diary-blob-key-v1", *master[0]) != 0)
|
||||
file_key: [32]u8
|
||||
check_true("the file's key", HmacSha256Text(*master[0], 32, hash, *file_key[0]) != 0)
|
||||
sealed: [7016]u8
|
||||
nonce: [12]u8
|
||||
aad := "inbe.diary.blob.v1"
|
||||
aad_bytes := cast(*TextDescriptor)(*aad)
|
||||
check_true("seal the old copy", ChaCha20Poly1305Seal(*file_key[0], *nonce[0], descriptor.data, image.count,
|
||||
aad_bytes.data, aad.count, *sealed[0], 7016) != 0)
|
||||
address_bytes: [65]u8
|
||||
storage_sha256_hex(*sealed[0], 7016, *address_bytes[0])
|
||||
address := TextFromCString(*address_bytes[0])
|
||||
key_hex: [65]u8
|
||||
unused BytesToHex(*file_key[0], 32, *key_hex[0], 65)
|
||||
old_path := PackageText("/api/v1/blobs/inbe/", address)
|
||||
answer: [64]u8
|
||||
status: s32 = 0
|
||||
length: s64 = 0
|
||||
check_int("a released version puts its old copy on the node",
|
||||
SendStoredBlob(url, "PUT", old_path, TextFromBytes(sealed[:]), answer[:], *status, *length), 0)
|
||||
check_int("the node keeps it", status, 204)
|
||||
check_int("at the photo's size plus 16 bytes", server_app_blob_size("/", "inbe", address), 7016)
|
||||
old_out: Vec(u8)
|
||||
BuilderPrint(*old_out, "{\"hash\":\"%\",\"size\":7000,\"type\":\"png\",\"name\":\"Old.png\",", hash)
|
||||
BuilderPrint(*old_out, "\"day\":\"2024-05-01\",\"taken\":\"2024-05-01\",\"added\":1792000000,\"capture\":0,")
|
||||
BuilderPrint(*old_out, "\"trashed\":0,\"blob\":\"%\",\"key\":\"%\"}", address, TextFromCString(*key_hex[0]))
|
||||
old_record := BuilderFinish(old_out)
|
||||
old_key := PackageText("cell.media.", hash)
|
||||
storage_set_setting_text(old_key, old_record)
|
||||
server_move_steps()
|
||||
check_true("without its bytes the photo waits", !MediaRead(hash).entity)
|
||||
DiaryBlobsSendNative(url)
|
||||
check_true("its old copy comes", PackageRead(MediaPath(hash, false), DIARY_FILE_LIMIT) == image)
|
||||
server_move_steps()
|
||||
check_true("then it moves", MediaRead(hash).entity)
|
||||
synchronize(url)
|
||||
DiaryBlobsSendNative(url)
|
||||
synchronize(url)
|
||||
check_int("the old copy stays until the photo comes back whole", server_app_blob_size("/", "inbe", address), 7016)
|
||||
DiaryBlobsSendNative(url)
|
||||
server_move_steps()
|
||||
check_true("its old record names the photo", FieldAt(storage_get_setting_text(old_key), 0, "photo") >= 0)
|
||||
synchronize(url)
|
||||
DiaryBlobsSendNative(url)
|
||||
check_true("the node deleted the old copy", server_app_blob_size("/", "inbe", address) <= 0)
|
||||
record := MediaEntityRecord(hash)
|
||||
content := EntityPhotoContent(record)
|
||||
PackageFree(record)
|
||||
check_int("the node keeps the photo's chunk", server_blob_size("/", TextUntilNul(content.chunks[0].address[:])), 7016)
|
||||
check_true("the old record keeps every field", FieldAt(storage_get_setting_text(old_key), 0, "blob") >= 0 &&
|
||||
FieldAt(storage_get_setting_text(old_key), 0, "name") >= 0)
|
||||
SecureWipe(*master[0], 32)
|
||||
SecureWipe(*file_key[0], 32)
|
||||
PackageFree(old_key)
|
||||
PackageFree(old_record)
|
||||
PackageFree(old_path)
|
||||
PackageFree(hash)
|
||||
}
|
||||
|
||||
// A photo added to the library on one device appears on the other with its
|
||||
// preview, and opens its original there. Copies go to every node whose
|
||||
// photo upload is on and not to one where it is off, each node on its own
|
||||
@@ -272,15 +376,13 @@ expect_library_copies :: (url: string, second: string, a: string, b: string) {
|
||||
hash_bytes: [65]u8
|
||||
unused AppCopyText(TextFromBytes(added.hash[:64]), hash_bytes[:])
|
||||
hash := TextUntilNul(hash_bytes[:])
|
||||
item_key := MediaRecordKey(hash)
|
||||
preview_key := MediaPreviewKey(hash)
|
||||
check_true("a made a preview", MediaRecordRead(preview_key).count > 0)
|
||||
check_true("a made a preview", EntityPreviewContent(MediaEntityRecord(hash)).valid)
|
||||
synchronize(url)
|
||||
DiaryBlobsSendNative(url)
|
||||
original_blob: [65]u8
|
||||
preview_blob: [65]u8
|
||||
check_int("the original's copy is named", cast(s32)library_record_blob(item_key, original_blob[:]).count, 64)
|
||||
check_int("the preview's copy is named", cast(s32)library_record_blob(preview_key, preview_blob[:]).count, 64)
|
||||
check_int("the original's chunk is named", cast(s32)library_record_blob(hash, false, original_blob[:]).count, 64)
|
||||
check_int("the preview's chunk is named", cast(s32)library_record_blob(hash, true, preview_blob[:]).count, 64)
|
||||
check_int("the second node keeps the original sealed",
|
||||
server_blob_size("/second/", TextUntilNul(original_blob[:])), 9016)
|
||||
check_true("the second node keeps the preview",
|
||||
@@ -303,7 +405,8 @@ expect_library_copies :: (url: string, second: string, a: string, b: string) {
|
||||
open_client(b)
|
||||
check_true("b adds the second node", SyncNodeAdd(second))
|
||||
synchronize(url)
|
||||
check_int("the photo is in b's library", MediaQuery("", false), 1)
|
||||
// The photo of the photo check is there too.
|
||||
check_int("the photo is in b's library", MediaQuery("", false), 2)
|
||||
check_true("its preview waits on b", MediaAsset(hash, false) == "")
|
||||
DiaryBlobsSendNative(url)
|
||||
preview_asset := PackageText(MediaAsset(hash, false), "")
|
||||
@@ -325,8 +428,6 @@ expect_library_copies :: (url: string, second: string, a: string, b: string) {
|
||||
check_int("the sync node now keeps the original", server_blob_size("/", TextUntilNul(original_blob[:])), 9016)
|
||||
check_true("and the preview", server_blob_size("/", TextUntilNul(preview_blob[:])) > 16)
|
||||
check_true("still nothing is sent twice", !DiaryBlobPlan(*pass, url))
|
||||
PackageFree(item_key)
|
||||
PackageFree(preview_key)
|
||||
MediaStoreClose()
|
||||
}
|
||||
|
||||
@@ -507,6 +608,7 @@ Check :: () -> s32 {
|
||||
check_int("live activity does not duplicate results", storage_session_count(), 1)
|
||||
expect_photo_copy(url, a, b)
|
||||
expect_library_copies(url, second_url, a, b)
|
||||
expect_old_copy_moves(url, a)
|
||||
open_client(b)
|
||||
check_true("complete the item", storage_elist_update_item(item_text, "Pack bag", "Passport", 1, 0) != 0)
|
||||
synchronize(url)
|
||||
|
||||
@@ -34,7 +34,7 @@ int main(void)
|
||||
{
|
||||
int result = Check();
|
||||
if (result != 0) fprintf(stderr, "sync server check failed with code %d\n", result);
|
||||
if (result == 0) puts("PASS two-client sync, habit/session/list/alias/friend recovery, Diary photo copies, library photos on two nodes, offline retry, conflict, backup restore, deletion");
|
||||
if (result == 0) puts("PASS two-client sync, habit/session/list/alias/friend recovery, entity photos and their chunks, library photos on two nodes, an old copy moved then deleted, offline retry, conflict, backup restore, deletion");
|
||||
return result == 0 ? 0 : 1;
|
||||
}
|
||||
C
|
||||
|
||||
Reference in new issue
Block a user