drone-path-archive 2.0.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,22 +1,32 @@
1
1
  # drone-path-archive
2
2
 
3
- Index and query a local library of DJI drone recordings. This package owns
4
- recording discovery, the SQLite archive store, flight grouping, spatial and
5
- camera-gaze search, kinematic shot-segment queries, and combined HTML map and
6
- track exports. It uses `drone-path-core` for telemetry extraction and spatial
7
- math.
3
+ Build a searchable library of local DJI recordings in a SQLite database. Discover
4
+ recordings, group clips into flights, filter by tag, search by location or camera
5
+ direction, and export a combined HTML map or track file.
6
+
7
+ ## Install
8
+
9
+ Requires Node.js 24 or later.
8
10
 
9
11
  ```sh
10
12
  npm install drone-path-archive
11
13
  ```
12
14
 
13
- Use the module subpaths in Node.js 24 or later.
15
+ ## Query an indexed archive
16
+
17
+ Given an existing `archive.sqlite` database (for example, one populated by
18
+ [`drone-path archive scan`](https://github.com/MrManny/drone-path/blob/main/docs/user/cli.md#scan-a-recording-library)),
19
+ list clips tagged `Golden hour`:
14
20
 
15
21
  ```js
16
- import { scanArchive } from 'drone-path-archive/indexed-scan';
17
- import { listArchive, nearArchive } from 'drone-path-archive/query';
22
+ import { listArchive } from 'drone-path-archive/query';
23
+
24
+ const clips = listArchive('./archive.sqlite', { tags: ['Golden hour'] });
25
+ console.log(clips.map((clip) => clip.path));
18
26
  ```
19
27
 
28
+ ## TypeScript
29
+
20
30
  Each module ships TypeScript declarations.
21
31
 
22
32
  Install `@types/node` for your Node.js major version. In TypeScript 6, list
@@ -31,6 +41,9 @@ Install `@types/node` for your Node.js major version. In TypeScript 6, list
31
41
  }
32
42
  ```
33
43
 
34
- See the [project manual](https://github.com/MrManny/drone-path/tree/main/docs/user)
35
- for archive indexing, search filters, and export formats. Install `drone-path`
36
- for the command-line interface.
44
+ ## Learn more
45
+
46
+ Use the [`drone-path` CLI](https://www.npmjs.com/package/drone-path) to scan and
47
+ search recordings without writing code. See the
48
+ [Archive guide](https://github.com/MrManny/drone-path/blob/main/docs/user/archive.md)
49
+ for indexing, search, and export options.
package/dist/export.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { ArchiveSegment, ListFilters } from './query.js';
3
3
  interface ExportOptions {
4
4
  filters?: ListFilters;
5
5
  flightIds?: readonly string[];
6
+ clipKeys?: readonly string[];
6
7
  redactLaunchM?: number;
7
8
  includeGaze?: boolean;
8
9
  }
package/dist/export.js CHANGED
@@ -13,15 +13,17 @@ import { groupFlightMembers } from './flight-members.js';
13
13
  import { assertNotArchiveFiles } from './output-guard.js';
14
14
  import { listArchiveSegments, matchesMetadata, segmentFilterOf } from './query.js';
15
15
  import { withArchiveStore } from './store.js';
16
- function exportFlights(db, { filters = {}, flightIds, redactLaunchM = 0, includeGaze = false }, splitDateline = false) {
16
+ function exportFlights(db, { filters = {}, flightIds, clipKeys, redactLaunchM = 0, includeGaze = false }, splitDateline = false) {
17
17
  if (!Number.isFinite(redactLaunchM) || redactLaunchM < 0) {
18
18
  throw new Error('expected a nonnegative launch redaction radius in meters');
19
19
  }
20
20
  const redact = redactLaunchM > 0;
21
21
  const segmentFilter = segmentFilterOf(filters);
22
22
  const selectedFlightIds = flightIds === undefined ? undefined : new Set(flightIds);
23
+ const selectedClipKeys = clipKeys === undefined ? undefined : new Set(clipKeys);
23
24
  return withArchiveStore(db, (store) => {
24
- const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ record, flight }) => (selectedFlightIds === undefined || selectedFlightIds.has(flight.flightId)) && matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact }, segmentFilter);
25
+ const { clips, endpoints } = store.readExportCandidates(filters.bbox, filters.availability, ({ key, record, flight }) => (selectedFlightIds === undefined || selectedFlightIds.has(flight.flightId)) &&
26
+ (selectedClipKeys === undefined || selectedClipKeys.has(key)) && matchesMetadata(record, filters), { redact, includeGaze: includeGaze && !redact }, segmentFilter, filters.tags);
25
27
  const redactTrack = launchRedactor(endpoints, redactLaunchM);
26
28
  const flights = groupFlightMembers(clips);
27
29
  return [...flights.values()].flatMap((members) => {
package/dist/query.d.ts CHANGED
@@ -2,11 +2,12 @@ import type { Bbox, LatLon } from 'drone-path-core/geo';
2
2
  import type { KinematicShot, ShotType } from 'drone-path-core/shot-segmentation';
3
3
  import type { ScanRecord } from './scanner.js';
4
4
  import type { IndexedClip, SegmentFilter } from './store.js';
5
- export { dateRangeToBounds, parseDateBound } from './camera-time.js';
5
+ export { parseDateBound } from './camera-time.js';
6
6
  export declare const DEFAULT_RADIUS_M = 100;
7
7
  export type ArchiveAvailability = IndexedClip['availability'];
8
8
  export type ArchiveClip = ScanRecord & {
9
9
  availability: ArchiveAvailability;
10
+ tags: string[];
10
11
  };
11
12
  export type FlightListClip = ArchiveClip & {
12
13
  splitFromKey: string | null;
@@ -28,6 +29,7 @@ export interface ListFilters {
28
29
  availability?: ArchiveAvailability;
29
30
  segmentType?: ShotType;
30
31
  minSmoothness?: number;
32
+ tags?: readonly string[];
31
33
  }
32
34
  export interface ArchiveSegment extends KinematicShot {
33
35
  clip: ArchiveClip;
@@ -41,6 +43,8 @@ export interface NearHit {
41
43
  export declare function segmentFilterOf({ segmentType, minSmoothness }: ListFilters): SegmentFilter | undefined;
42
44
  export declare function matchesMetadata(clip: ScanRecord, { afterMs, beforeMs, minDistanceM, minDurationSec, maxDurationSec, hasGps, query }: ListFilters): boolean;
43
45
  export declare function listArchive(db: string, filters?: ListFilters): ArchiveClip[];
46
+ /** Like {@link listArchive}, but each clip's `track` is the small decimated overview, not the full track. */
47
+ export declare function listArchiveClipOverviews(db: string, filters?: ListFilters): ArchiveClip[];
44
48
  /** Reads only the video metadata of the indexed clips at `paths`, keyed by the requested path. */
45
49
  export declare function readArchiveVideos(db: string, paths: readonly string[]): Map<string, NonNullable<ScanRecord['video']>>;
46
50
  export declare function listArchiveVideos(db: string): {
@@ -52,5 +56,8 @@ export declare function listArchiveFlights(db: string, filters?: ListFilters, op
52
56
  }): ArchiveFlight[];
53
57
  export declare function listArchiveFlightOverviews(db: string, filters?: ListFilters): ArchiveFlight[];
54
58
  export declare function listArchiveSegments(db: string, filters?: ListFilters): ArchiveSegment[];
55
- export declare function nearArchive(db: string, point: LatLon, radiusM?: number, includeGaze?: boolean): NearHit[];
59
+ export declare function nearArchive(db: string, point: LatLon, radiusM?: number, includeGaze?: boolean, tags?: readonly string[]): NearHit[];
60
+ export declare function readArchiveClipTags(db: string, indexedPaths: readonly string[]): Map<string, string[]>;
61
+ /** Updates an already-indexed path and returns its current tags without opening the recording. */
62
+ export declare function updateArchiveClipTags(db: string, indexedPath: string, operation: 'add' | 'remove', tags: readonly string[]): string[];
56
63
  export declare function pruneArchiveOffline(db: string): number;
package/dist/query.js CHANGED
@@ -4,7 +4,7 @@ import { zonedTimeMs } from './camera-time.js';
4
4
  import { groupFlightMembers } from './flight-members.js';
5
5
  import { groupSamples } from './scan-track.js';
6
6
  import { archiveClipKey, withArchiveStore } from './store.js';
7
- export { dateRangeToBounds, parseDateBound } from './camera-time.js';
7
+ export { parseDateBound } from './camera-time.js';
8
8
  export const DEFAULT_RADIUS_M = 100;
9
9
  export function segmentFilterOf({ segmentType, minSmoothness }) {
10
10
  if (minSmoothness !== undefined && (!Number.isFinite(minSmoothness) || minSmoothness < 0 || minSmoothness > 1)) {
@@ -50,15 +50,15 @@ export function matchesMetadata(clip, { afterMs, beforeMs, minDistanceM, minDura
50
50
  (afterMs === undefined || time >= afterMs) &&
51
51
  (beforeMs === undefined || time < beforeMs);
52
52
  }
53
- function toClip({ record, availability }) {
54
- return { ...record, availability };
53
+ function toClip({ record, availability, tags }) {
54
+ return { ...record, availability, tags };
55
55
  }
56
56
  function matchingClips(store, filters, overview = false) {
57
57
  validateDurationBounds(filters);
58
58
  const segmentFilter = segmentFilterOf(filters);
59
59
  const clips = overview
60
- ? store.listClipOverviews(filters.bbox, filters.availability, segmentFilter)
61
- : store.listClips(filters.bbox, filters.availability, segmentFilter);
60
+ ? store.listClipOverviews(filters.bbox, filters.availability, segmentFilter, filters.tags)
61
+ : store.listClips(filters.bbox, filters.availability, segmentFilter, filters.tags);
62
62
  return clips.flatMap((indexed) => {
63
63
  const clip = toClip(indexed);
64
64
  return matchesMetadata(clip, filters) ? [{ clip, flight: indexed.flight }] : [];
@@ -67,6 +67,10 @@ function matchingClips(store, filters, overview = false) {
67
67
  export function listArchive(db, filters = {}) {
68
68
  return withArchiveStore(db, (store) => matchingClips(store, filters).map(({ clip }) => clip));
69
69
  }
70
+ /** Like {@link listArchive}, but each clip's `track` is the small decimated overview, not the full track. */
71
+ export function listArchiveClipOverviews(db, filters = {}) {
72
+ return withArchiveStore(db, (store) => matchingClips(store, filters, true).map(({ clip }) => clip));
73
+ }
70
74
  /** Reads only the video metadata of the indexed clips at `paths`, keyed by the requested path. */
71
75
  export function readArchiveVideos(db, paths) {
72
76
  const keys = [...new Set(paths.map(archiveClipKey))];
@@ -109,15 +113,16 @@ export function listArchiveSegments(db, filters = {}) {
109
113
  availability: filters.availability,
110
114
  segmentType: segmentFilter?.segmentType,
111
115
  minSmoothness: segmentFilter?.minSmoothness,
116
+ tags: filters.tags,
112
117
  }).flatMap(({ clip: indexed, segment }) => {
113
118
  const clip = toClip(indexed);
114
119
  return matchesMetadata(clip, filters) ? [{ clip, ...segment }] : [];
115
120
  }));
116
121
  }
117
- export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze = false) {
122
+ export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze = false, tags) {
118
123
  return withArchiveStore(db, (store) => {
119
124
  const hits = [];
120
- const { tracks, gaze } = store.readNearCandidates(radiusBbox(point, radiusM), includeGaze ? point : undefined);
125
+ const { tracks, gaze } = store.readNearCandidates(radiusBbox(point, radiusM), includeGaze ? point : undefined, tags);
121
126
  for (const { clip, samples } of tracks) {
122
127
  const match = nearestOnTrack(point, groupSamples(samples));
123
128
  if (match !== null && match.distanceM <= radiusM) {
@@ -133,6 +138,16 @@ export function nearArchive(db, point, radiusM = DEFAULT_RADIUS_M, includeGaze =
133
138
  return hits.sort((a, b) => a.distanceM - b.distanceM);
134
139
  });
135
140
  }
141
+ export function readArchiveClipTags(db, indexedPaths) {
142
+ if (indexedPaths.length === 0)
143
+ return new Map();
144
+ const tags = withArchiveStore(db, (store) => store.readTagsForClips(indexedPaths.map(archiveClipKey)));
145
+ return new Map(indexedPaths.map((file) => [file, tags.get(archiveClipKey(file)) ?? []]));
146
+ }
147
+ /** Updates an already-indexed path and returns its current tags without opening the recording. */
148
+ export function updateArchiveClipTags(db, indexedPath, operation, tags) {
149
+ return withArchiveStore(db, (store) => store.updateClipTags(archiveClipKey(indexedPath), operation, tags));
150
+ }
136
151
  export function pruneArchiveOffline(db) {
137
152
  return withArchiveStore(db, (store) => store.pruneOffline());
138
153
  }
package/dist/scanner.d.ts CHANGED
@@ -41,6 +41,5 @@ export interface ScanOptions {
41
41
  }
42
42
  export declare function discoverRecordings(dirs: readonly string[], { recurse, signal }?: Pick<ScanOptions, 'recurse' | 'signal'>): Promise<string[]>;
43
43
  export declare function scanRecording(file: string, { tools, signal, sidecarFor, onTrack, onGaze, onSegments }: Pick<ScanOptions, 'tools' | 'signal' | 'sidecarFor' | 'onTrack' | 'onGaze' | 'onSegments'>): Promise<ScanRecord>;
44
- export declare function scanFolders(dirs: readonly string[], options: ScanOptions): Promise<ScanRecord[]>;
45
44
  export declare function scanRecordings(files: readonly string[], options: ScanOptions): Promise<ScanRecord[]>;
46
45
  export {};
package/dist/scanner.js CHANGED
@@ -75,10 +75,6 @@ export async function scanRecording(file, { tools, signal, sidecarFor, onTrack,
75
75
  }
76
76
  return record;
77
77
  }
78
- export async function scanFolders(dirs, options) {
79
- const files = await discoverRecordings(dirs, options);
80
- return scanRecordings(files, options);
81
- }
82
78
  export async function scanRecordings(files, options) {
83
79
  const queue = new PQueue({ concurrency: options.concurrency ?? 4 });
84
80
  // Wait for active tasks to release their file handles and child processes after abort.
@@ -48,6 +48,7 @@ export interface ArchiveSharpnessTimeline {
48
48
  clipPath: string;
49
49
  clipKey: string;
50
50
  availability: ArchiveAvailability;
51
+ tags: string[];
51
52
  analyzed: boolean;
52
53
  run: ArchiveSharpnessRun | null;
53
54
  totalSamples: number;
@@ -68,6 +69,7 @@ export interface ExportArchiveSharpnessNdjsonResult {
68
69
  clipPath: string;
69
70
  clipKey: string;
70
71
  availability: ArchiveAvailability;
72
+ tags: string[];
71
73
  run: ArchiveSharpnessRun;
72
74
  count: number;
73
75
  ndjson: string;
package/dist/sharpness.js CHANGED
@@ -124,7 +124,7 @@ function recordingChanged(resolvedPath) {
124
124
  return new Error(`recording changed during sharpness analysis, rerun: ${resolvedPath}`);
125
125
  }
126
126
  async function indexSingleClip(db, resolvedPath, key, input, tools, signal, assertAllowedPath) {
127
- const revision = withArchiveStore(db, (store) => store.currentRevision());
127
+ const revision = withArchiveStore(db, (store) => store.currentIndexRevision());
128
128
  const { sidecar, fingerprint } = input;
129
129
  // Re-check right before the scan reads the sidecar: awaiting the tools widens the swap window.
130
130
  if (sidecar !== null)
@@ -165,10 +165,10 @@ async function indexSingleClip(db, resolvedPath, key, input, tools, signal, asse
165
165
  gaze,
166
166
  segments,
167
167
  };
168
- withArchiveStore(db, (store) => {
168
+ return withArchiveStore(db, (store) => {
169
169
  store.commit(revision, [update], [], [], []);
170
+ return { ...update, tags: store.readTagsForClips([key]).get(key) ?? [] };
170
171
  });
171
- return update;
172
172
  }
173
173
  /** Run or reuse opt-in clip-wide sharpness analysis and atomically persist the result in SQLite. */
174
174
  export async function analyzeArchiveSharpness(db, videoPath, options) {
@@ -226,7 +226,7 @@ export async function analyzeArchiveSharpness(db, videoPath, options) {
226
226
  }));
227
227
  if (cachedRun) {
228
228
  return {
229
- clip: { ...indexed.record, availability: indexed.availability },
229
+ clip: { ...indexed.record, availability: indexed.availability, tags: indexed.tags },
230
230
  clipKey: key,
231
231
  cached: true,
232
232
  run: decodeArchiveRun(cachedRun),
@@ -258,7 +258,7 @@ export async function analyzeArchiveSharpness(db, videoPath, options) {
258
258
  samples: analyzed.samples,
259
259
  }));
260
260
  return {
261
- clip: { ...indexed.record, availability: indexed.availability },
261
+ clip: { ...indexed.record, availability: indexed.availability, tags: indexed.tags },
262
262
  clipKey: key,
263
263
  cached: false,
264
264
  run: decodeArchiveRun(saved),
@@ -284,6 +284,7 @@ export function getArchiveSharpness(db, videoPath, options = {}) {
284
284
  clipPath: clip.record.path,
285
285
  clipKey: clip.key,
286
286
  availability: clip.availability,
287
+ tags: clip.tags,
287
288
  analyzed: false,
288
289
  run: null,
289
290
  totalSamples: 0,
@@ -307,6 +308,7 @@ export function getArchiveSharpness(db, videoPath, options = {}) {
307
308
  clipPath: clip.record.path,
308
309
  clipKey: clip.key,
309
310
  availability: clip.availability,
311
+ tags: clip.tags,
310
312
  analyzed: true,
311
313
  run: decodeArchiveRun(run),
312
314
  totalSamples,
@@ -345,6 +347,7 @@ export function exportArchiveSharpnessNdjson(db, videoPath, options = {}) {
345
347
  clipPath: clip.record.path,
346
348
  clipKey: clip.key,
347
349
  availability: clip.availability,
350
+ tags: clip.tags,
348
351
  run: decodeArchiveRun(run),
349
352
  count: samples.length,
350
353
  ndjson,
package/dist/store.d.ts CHANGED
@@ -6,7 +6,7 @@ import type { GazeSample } from './gaze.js';
6
6
  import type { ScanPoint, SparseSample } from './scan-track.js';
7
7
  import type { ScanRecord } from './scanner.js';
8
8
  type ArchiveVideo = NonNullable<ScanRecord['video']>;
9
- export declare const ARCHIVE_SCHEMA_VERSION = 5;
9
+ export declare const ARCHIVE_SCHEMA_VERSION = 7;
10
10
  export declare const CLIP_FINGERPRINT_VERSION = 1;
11
11
  export declare function archiveClipKey(filePath: string): string;
12
12
  export interface SegmentFilter {
@@ -32,7 +32,10 @@ export interface ClipUpdate extends IndexedClip {
32
32
  gaze?: GazeSample[];
33
33
  segments?: KinematicShot[];
34
34
  }
35
- export interface IndexedFlightClip extends IndexedClip {
35
+ export interface TaggedIndexedClip extends IndexedClip {
36
+ tags: string[];
37
+ }
38
+ export interface IndexedFlightClip extends TaggedIndexedClip {
36
39
  flight: FlightMembership;
37
40
  }
38
41
  export interface SharpnessRunRecord {
@@ -64,6 +67,8 @@ export interface SharpnessSampleFilter {
64
67
  type SharpnessRunKey = Pick<SharpnessRunRecord, 'clipKey' | 'fingerprintKey' | 'method' | 'version' | 'settingsJson'>;
65
68
  export declare class ArchiveStore {
66
69
  private readonly db;
70
+ private readonly statements;
71
+ private samplesByClipStatement?;
67
72
  constructor(file: string);
68
73
  private ensureFlightIndexes;
69
74
  private schemaVersion;
@@ -77,24 +82,27 @@ export declare class ArchiveStore {
77
82
  })[];
78
83
  };
79
84
  currentRevision(): number;
85
+ currentIndexRevision(): number;
80
86
  availabilityOf(key: string): IndexedClip['availability'] | null;
81
87
  indexedPaths(): string[];
82
88
  indexedVideos(): {
83
89
  path: string;
84
90
  video: ScanRecord['video'];
85
91
  }[];
86
- listClips(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
87
- listClipOverviews(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter): IndexedFlightClip[];
88
- private clipMatchesViewport;
92
+ listClips(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter, tags?: readonly string[]): IndexedFlightClip[];
93
+ listClipOverviews(bbox?: Bbox, availability?: IndexedClip['availability'], segmentFilter?: SegmentFilter, tags?: readonly string[]): IndexedFlightClip[];
94
+ private viewportMatcher;
95
+ private readRecordTracksByClip;
89
96
  private selectClipViewport;
90
97
  readExportCandidates(bbox: Bbox | undefined, availability: IndexedClip['availability'] | undefined, matches: (clip: IndexedFlightClip) => boolean, options: {
91
98
  includeGaze: boolean;
92
99
  redact: boolean;
93
- }, segmentFilter?: SegmentFilter): {
100
+ }, segmentFilter?: SegmentFilter, tags?: readonly string[]): {
94
101
  endpoints: LatLon[];
95
102
  clips: {
96
103
  gaze: GazeSample[];
97
104
  flight: FlightMembership;
105
+ tags: string[];
98
106
  key: string;
99
107
  record: ScanRecord;
100
108
  fingerprint: ClipFingerprint;
@@ -102,25 +110,22 @@ export declare class ArchiveStore {
102
110
  }[];
103
111
  };
104
112
  private readLaunchEndpoints;
105
- readTrackCandidates(bbox: Bbox): {
106
- clip: IndexedClip;
107
- samples: SparseSample[];
108
- }[];
109
- readNearCandidates(bbox: Bbox, point?: LatLon): {
113
+ readNearCandidates(bbox: Bbox, point?: LatLon, tags?: readonly string[]): {
110
114
  tracks: {
111
115
  clip: IndexedFlightClip;
112
116
  samples: SparseSample[];
113
117
  }[];
114
118
  gaze: {
115
- clip: IndexedClip;
119
+ clip: TaggedIndexedClip;
116
120
  samples: GazeSample[];
117
121
  }[];
118
122
  };
119
123
  private selectGazeCandidates;
120
- readOverview(key: string): ScanPoint[][];
121
- readSamples(key: string): SparseSample[];
122
- readSegments(key: string): KinematicShot[];
123
- getClipByKey(key: string): IndexedClip | null;
124
+ private readSamplesByClip;
125
+ getClipByKey(key: string): TaggedIndexedClip | null;
126
+ readTagsForClips(keys: readonly string[]): Map<string, string[]>;
127
+ listTags(): string[];
128
+ updateClipTags(key: string, operation: 'add' | 'remove', tags: readonly string[]): string[];
124
129
  readClipVideos(keys: readonly string[]): Map<string, ArchiveVideo>;
125
130
  getSharpnessRun(runId: number): SharpnessRunRecord | null;
126
131
  findSharpnessRun(query: SharpnessRunKey): SharpnessRunRecord | null;
@@ -140,18 +145,23 @@ export declare class ArchiveStore {
140
145
  availability?: IndexedClip['availability'];
141
146
  segmentType?: ShotType;
142
147
  minSmoothness?: number;
148
+ tags?: readonly string[];
143
149
  }): {
144
- clip: IndexedClip;
150
+ clip: TaggedIndexedClip;
145
151
  segment: KinematicShot;
146
152
  }[];
147
153
  commit(expectedRevision: number, updates: readonly ClipUpdate[], online: readonly string[], offline: readonly string[], removed: readonly string[]): void;
148
154
  removeClipsUnder(root: string): number;
149
155
  pruneOffline(): number;
150
- private revision;
156
+ private bumpIndexRevision;
151
157
  private clipFilterClauses;
152
158
  private selectClips;
153
159
  readFlightStartTimes(flightIds: readonly string[]): Map<string, string | null>;
160
+ /** Regroup the streams that hold `changedKeys` (every clip when omitted); other memberships cannot change. */
154
161
  private refreshFlights;
162
+ /** Flight streams never span directories (`groupFlights` partitions by `path.dirname`). */
163
+ private clipKeysInDirectories;
164
+ private statement;
155
165
  private transaction;
156
166
  private writeClip;
157
167
  private writeGaze;
package/dist/store.js CHANGED
@@ -7,7 +7,8 @@ import { bboxIntersects, longitudeRanges, resolveTrackBbox } from 'drone-path-co
7
7
  import { zonedTimeMs } from './camera-time.js';
8
8
  import { gazeBbox } from './gaze.js';
9
9
  import { groupSamples } from './scan-track.js';
10
- export const ARCHIVE_SCHEMA_VERSION = 5;
10
+ import { archiveTagKey, parseArchiveTags } from './tags.js';
11
+ export const ARCHIVE_SCHEMA_VERSION = 7;
11
12
  export const CLIP_FINGERPRINT_VERSION = 1;
12
13
  export function archiveClipKey(filePath) {
13
14
  return process.platform === 'win32' ? filePath.toLowerCase() : filePath;
@@ -26,12 +27,15 @@ function decodeClip(row) {
26
27
  }
27
28
  function decodeFlightClip(row) {
28
29
  return {
29
- ...decodeClip(row),
30
+ ...decodeTaggedClip(row),
30
31
  flight: {
31
32
  key: row.clip_key, flightId: row.flight_id, order: row.flight_order, splitFromKey: row.split_from_key,
32
33
  },
33
34
  };
34
35
  }
36
+ function decodeTaggedClip(row) {
37
+ return { ...decodeClip(row), tags: JSON.parse(row.tags_json) };
38
+ }
35
39
  function decodeClipOverview(row) {
36
40
  const clip = decodeFlightClip(row);
37
41
  return {
@@ -183,8 +187,54 @@ const SHARPNESS_SCHEMA = `
183
187
  CREATE INDEX IF NOT EXISTS sharpness_samples_run_time
184
188
  ON sharpness_samples (run_id, t_sec, frame_index);
185
189
  `;
190
+ const TAGS_SCHEMA = `
191
+ CREATE TABLE clip_tags (
192
+ file_name TEXT NOT NULL,
193
+ size INTEGER NOT NULL,
194
+ tag TEXT NOT NULL,
195
+ tag_key TEXT NOT NULL,
196
+ created_at INTEGER NOT NULL,
197
+ PRIMARY KEY (file_name, size, tag_key)
198
+ );
199
+ CREATE INDEX clip_tags_by_tag ON clip_tags(tag_key);
200
+ `;
201
+ const CLIP_TAG_IDENTITY = `file_name = clip_basename(json_extract(clips.record_json, '$.path'))
202
+ AND clip_tags.size = clips.size`;
203
+ const CLIP_TAGS_COLUMN = `(SELECT json_group_array(tag ORDER BY tag_key) FROM clip_tags
204
+ WHERE ${CLIP_TAG_IDENTITY}) AS tags_json`;
205
+ function clipTagFilter(tags) {
206
+ if (!tags?.length)
207
+ return { clause: '', values: [] };
208
+ return {
209
+ clause: `NOT EXISTS (
210
+ SELECT 1 FROM json_each(?) AS requested WHERE NOT EXISTS (
211
+ SELECT 1 FROM clip_tags WHERE ${CLIP_TAG_IDENTITY} AND tag_key = requested.value
212
+ )
213
+ )`,
214
+ values: [JSON.stringify(parseArchiveTags(tags).map(archiveTagKey))],
215
+ };
216
+ }
217
+ /** Smallest string above every string that starts with `prefix` in SQLite's binary (UTF-8) order, if cheaply known. */
218
+ function prefixUpperBound(prefix) {
219
+ const last = prefix.charCodeAt(prefix.length - 1);
220
+ if (!(last < 0xd7ff))
221
+ return null;
222
+ return prefix.slice(0, -1) + String.fromCharCode(last + 1);
223
+ }
224
+ function clipMatchesViewport(bbox, raw, track, samples) {
225
+ if (raw === null)
226
+ return false;
227
+ if (!spansAntimeridian(raw))
228
+ return true;
229
+ return bboxIntersects(bbox, resolveTrackBbox(raw, [...track, ...groupSamples(samples)]));
230
+ }
231
+ function spansAntimeridian(raw) {
232
+ return raw !== null && raw.maxLon - raw.minLon > 180;
233
+ }
186
234
  export class ArchiveStore {
187
235
  db;
236
+ statements = new Map();
237
+ samplesByClipStatement;
188
238
  constructor(file) {
189
239
  if (file !== ':memory:')
190
240
  mkdirSync(path.dirname(file), { recursive: true });
@@ -192,6 +242,7 @@ export class ArchiveStore {
192
242
  try {
193
243
  this.db.exec('PRAGMA busy_timeout = 5000');
194
244
  this.db.exec('PRAGMA foreign_keys = ON');
245
+ this.db.function('clip_basename', { deterministic: true }, (file) => typeof file === 'string' ? path.basename(file) : null);
195
246
  if (this.schemaVersion() !== ARCHIVE_SCHEMA_VERSION)
196
247
  this.migrate();
197
248
  this.ensureFlightIndexes();
@@ -248,6 +299,15 @@ export class ArchiveStore {
248
299
  if (version < 5) {
249
300
  this.db.exec(SHARPNESS_SCHEMA);
250
301
  }
302
+ if (version < 6) {
303
+ this.db.exec(TAGS_SCHEMA);
304
+ }
305
+ if (version < 7) {
306
+ this.db.exec(`
307
+ ALTER TABLE archive_revision ADD COLUMN index_revision INTEGER NOT NULL DEFAULT 0;
308
+ UPDATE archive_revision SET index_revision = revision;
309
+ `);
310
+ }
251
311
  this.db.exec(`PRAGMA user_version = ${ARCHIVE_SCHEMA_VERSION}`);
252
312
  });
253
313
  }
@@ -256,7 +316,7 @@ export class ArchiveStore {
256
316
  }
257
317
  snapshot() {
258
318
  return this.transaction('BEGIN', () => ({
259
- revision: this.revision(),
319
+ revision: this.currentIndexRevision(),
260
320
  clips: this.db.prepare(`
261
321
  SELECT clips.*,
262
322
  clip_gaze.clip_key IS NULL AND
@@ -272,7 +332,10 @@ export class ArchiveStore {
272
332
  }));
273
333
  }
274
334
  currentRevision() {
275
- return this.revision();
335
+ return this.db.prepare('SELECT revision FROM archive_revision').get()?.revision;
336
+ }
337
+ currentIndexRevision() {
338
+ return this.db.prepare('SELECT index_revision FROM archive_revision').get()?.index_revision;
276
339
  }
277
340
  availabilityOf(key) {
278
341
  const row = this.db.prepare('SELECT availability FROM clips WHERE clip_key = ?').get(key);
@@ -294,33 +357,43 @@ export class ArchiveStore {
294
357
  ? [{ path: clip_path, video: video_json === null ? null : JSON.parse(video_json) }]
295
358
  : []));
296
359
  }
297
- listClips(bbox, availability, segmentFilter) {
360
+ listClips(bbox, availability, segmentFilter, tags) {
298
361
  if (bbox === undefined)
299
- return this.selectClips(undefined, availability, false, segmentFilter);
300
- return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter));
362
+ return this.selectClips(undefined, availability, false, segmentFilter, false, tags);
363
+ return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter, false, tags));
301
364
  }
302
- listClipOverviews(bbox, availability, segmentFilter) {
365
+ listClipOverviews(bbox, availability, segmentFilter, tags) {
303
366
  if (bbox === undefined)
304
- return this.selectClips(undefined, availability, false, segmentFilter, true);
305
- return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter, true));
306
- }
307
- clipMatchesViewport(bbox, key, record) {
308
- const raw = record.bbox;
309
- if (raw === null)
310
- return false;
311
- if (raw.maxLon - raw.minLon <= 180)
312
- return true;
313
- return bboxIntersects(bbox, resolveTrackBbox(raw, [...record.track, ...groupSamples(this.readSamples(key))]));
314
- }
315
- selectClipViewport(bbox, availability, segmentFilter, overviewOnly = false) {
316
- const clips = this.selectClips(bbox, availability, false, segmentFilter, overviewOnly);
367
+ return this.selectClips(undefined, availability, false, segmentFilter, true, tags);
368
+ return this.transaction('BEGIN', () => this.selectClipViewport(bbox, availability, segmentFilter, true, tags));
369
+ }
370
+ viewportMatcher(bbox, clips, overviewOnly = false) {
371
+ const wide = [...new Set(clips.filter(({ record }) => spansAntimeridian(record.bbox)).map(({ key }) => key))];
372
+ const samples = this.readSamplesByClip(wide);
373
+ // An overview record carries the decimated track, which can drop the fixes that reach the viewport.
374
+ const tracks = overviewOnly ? this.readRecordTracksByClip(wide) : undefined;
375
+ return ({ key, record }) => clipMatchesViewport(bbox, record.bbox, tracks ? tracks.get(key) ?? [] : record.track, samples.get(key) ?? []);
376
+ }
377
+ readRecordTracksByClip(keys) {
378
+ if (keys.length === 0)
379
+ return new Map();
380
+ const rows = this.db.prepare(`
381
+ SELECT clip_key, json_extract(record_json, '$.track') AS track_json FROM clips
382
+ WHERE clip_key IN (SELECT value FROM json_each(?))
383
+ `).all(JSON.stringify(keys));
384
+ return new Map(rows.map(({ clip_key, track_json }) => [
385
+ clip_key, track_json ? JSON.parse(track_json) : [],
386
+ ]));
387
+ }
388
+ selectClipViewport(bbox, availability, segmentFilter, overviewOnly = false, tags) {
389
+ const clips = this.selectClips(bbox, availability, false, segmentFilter, overviewOnly, tags);
317
390
  if (bbox === undefined)
318
391
  return clips;
319
- return clips.filter(({ key, record }) => this.clipMatchesViewport(bbox, key, record));
392
+ return clips.filter(this.viewportMatcher(bbox, clips, overviewOnly));
320
393
  }
321
- readExportCandidates(bbox, availability, matches, options, segmentFilter) {
394
+ readExportCandidates(bbox, availability, matches, options, segmentFilter, tags) {
322
395
  return this.transaction('BEGIN', () => {
323
- const clips = this.selectClipViewport(bbox, availability, segmentFilter).filter(matches);
396
+ const clips = this.selectClipViewport(bbox, availability, segmentFilter, false, tags).filter(matches);
324
397
  const endpoints = options.redact ? this.readLaunchEndpoints(new Set(clips.map(({ flight }) => flight.flightId))) : [];
325
398
  const gaze = options.includeGaze ? this.db.prepare('SELECT samples_json FROM clip_gaze WHERE clip_key = ?') : undefined;
326
399
  return {
@@ -351,45 +424,102 @@ export class ArchiveStore {
351
424
  }
352
425
  return endpoints;
353
426
  }
354
- readTrackCandidates(bbox) {
355
- return this.readNearCandidates(bbox).tracks;
356
- }
357
- readNearCandidates(bbox, point) {
358
- return this.transaction('BEGIN', () => ({
359
- tracks: this.selectClips(bbox, undefined, true).map((clip) => ({ clip, samples: this.readSamples(clip.key) })),
360
- gaze: point ? this.selectGazeCandidates(point) : [],
361
- }));
427
+ readNearCandidates(bbox, point, tags) {
428
+ return this.transaction('BEGIN', () => {
429
+ const clips = this.selectClips(bbox, undefined, true, undefined, false, tags);
430
+ const samples = this.readSamplesByClip(clips.map(({ key }) => key));
431
+ return {
432
+ tracks: clips.map((clip) => ({ clip, samples: samples.get(clip.key) ?? [] })),
433
+ gaze: point ? this.selectGazeCandidates(point, tags) : [],
434
+ };
435
+ });
362
436
  }
363
- selectGazeCandidates({ lat, lon }) {
437
+ selectGazeCandidates({ lat, lon }, tags) {
364
438
  const longitude = lon === 180 ? -180 : lon;
439
+ const filter = clipTagFilter(tags);
365
440
  const rows = this.db.prepare(`
366
- SELECT clips.*, samples_json FROM clips JOIN clip_gaze USING (clip_key)
441
+ SELECT clips.*, samples_json, ${CLIP_TAGS_COLUMN} FROM clips JOIN clip_gaze USING (clip_key)
367
442
  WHERE clip_gaze.min_lat <= ? AND clip_gaze.max_lat >= ?
368
443
  AND clip_gaze.min_lon <= ? AND clip_gaze.max_lon >= ?
444
+ ${filter.clause ? `AND ${filter.clause}` : ''}
369
445
  ORDER BY clip_key
370
- `).all(lat, lat, longitude, longitude);
371
- return rows.map((row) => ({ clip: decodeClip(row), samples: JSON.parse(row.samples_json) }));
446
+ `).all(lat, lat, longitude, longitude, ...filter.values);
447
+ return rows.map((row) => ({ clip: decodeTaggedClip(row), samples: JSON.parse(row.samples_json) }));
372
448
  }
373
- readOverview(key) {
374
- const row = this.db.prepare('SELECT overview_json FROM clips WHERE clip_key = ?').get(key);
375
- return row ? JSON.parse(row.overview_json) : [];
376
- }
377
- readSamples(key) {
378
- return this.db.prepare(`
379
- SELECT segment, lat, lon, t_sec AS tSec FROM clip_samples
380
- WHERE clip_key = ? ORDER BY segment, sample_index
381
- `).all(key);
382
- }
383
- readSegments(key) {
384
- const rows = this.db.prepare(`
385
- SELECT ${SEGMENT_COLUMNS}
386
- FROM segments WHERE clip_key = ? ORDER BY segment_index
387
- `).all(key);
388
- return rows.map(decodeSegment);
449
+ readSamplesByClip(keys) {
450
+ const samples = new Map(keys.map((key) => [key, []]));
451
+ if (keys.length === 0)
452
+ return samples;
453
+ if (this.samplesByClipStatement === undefined) {
454
+ this.samplesByClipStatement = this.db.prepare(`
455
+ SELECT clip_key, segment, lat, lon, t_sec FROM clip_samples
456
+ WHERE clip_key IN (SELECT value FROM json_each(?)) ORDER BY clip_key, segment, sample_index
457
+ `);
458
+ // Array rows skip per-row named-object materialization, which dominates this query's cost.
459
+ this.samplesByClipStatement.setReturnArrays(true);
460
+ }
461
+ const rows = this.samplesByClipStatement.all(JSON.stringify(keys));
462
+ let current;
463
+ let list;
464
+ for (const [key, segment, lat, lon, tSec] of rows) {
465
+ if (key !== current) {
466
+ current = key;
467
+ list = samples.get(key);
468
+ }
469
+ list?.push({ segment, lat, lon, tSec });
470
+ }
471
+ return samples;
389
472
  }
390
473
  getClipByKey(key) {
391
- const row = this.db.prepare('SELECT * FROM clips WHERE clip_key = ?').get(key);
392
- return row ? decodeClip(row) : null;
474
+ const row = this.statement(`SELECT clips.*, ${CLIP_TAGS_COLUMN} FROM clips WHERE clip_key = ?`)
475
+ .get(key);
476
+ return row ? decodeTaggedClip(row) : null;
477
+ }
478
+ readTagsForClips(keys) {
479
+ if (keys.length === 0)
480
+ return new Map();
481
+ const rows = this.statement(`
482
+ SELECT clip_key, ${CLIP_TAGS_COLUMN} FROM clips WHERE clip_key IN (SELECT value FROM json_each(?))
483
+ `).all(JSON.stringify(keys));
484
+ return new Map(rows.map(({ clip_key, tags_json }) => [clip_key, JSON.parse(tags_json)]));
485
+ }
486
+ listTags() {
487
+ return this.statement(`
488
+ SELECT tag FROM (
489
+ SELECT tag, tag_key, ROW_NUMBER() OVER (PARTITION BY tag_key ORDER BY created_at, rowid) AS first_added
490
+ FROM clip_tags
491
+ ) WHERE first_added = 1 ORDER BY tag_key
492
+ `)
493
+ .all().map(({ tag }) => tag);
494
+ }
495
+ updateClipTags(key, operation, tags) {
496
+ if (tags.length === 0)
497
+ throw new Error('expected at least one tag');
498
+ const values = parseArchiveTags(tags);
499
+ return this.transaction('BEGIN IMMEDIATE', () => {
500
+ const clip = this.statement(`
501
+ SELECT clip_basename(json_extract(record_json, '$.path')) AS file_name, size FROM clips WHERE clip_key = ?
502
+ `).get(key);
503
+ if (!clip)
504
+ throw new Error(`clip is not indexed: ${key}`);
505
+ const { file_name: fileName, size } = clip;
506
+ const write = operation === 'add'
507
+ ? this.statement('INSERT INTO clip_tags (file_name, size, tag, tag_key, created_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING')
508
+ : this.statement('DELETE FROM clip_tags WHERE file_name = ? AND size = ? AND tag_key = ?');
509
+ const now = Date.now();
510
+ let changed = false;
511
+ for (const tag of values) {
512
+ const tagKey = archiveTagKey(tag);
513
+ const { changes } = operation === 'add'
514
+ ? write.run(fileName, size, tag, tagKey, now)
515
+ : write.run(fileName, size, tagKey);
516
+ if (changes)
517
+ changed = true;
518
+ }
519
+ if (changed)
520
+ this.db.exec('UPDATE archive_revision SET revision = revision + 1');
521
+ return this.readTagsForClips([key]).get(key) ?? [];
522
+ });
393
523
  }
394
524
  readClipVideos(keys) {
395
525
  if (keys.length === 0)
@@ -529,25 +659,28 @@ export class ArchiveStore {
529
659
  }
530
660
  listSegments(filters = {}) {
531
661
  return this.transaction('BEGIN', () => {
532
- const { clauses, values } = this.clipFilterClauses(filters.bbox, filters.availability, false);
662
+ const { clauses, values } = this.clipFilterClauses(filters.bbox, filters.availability, false, undefined, filters.tags);
533
663
  const segment = segmentFilterClauses(filters);
534
664
  clauses.push(...segment.clauses);
535
665
  values.push(...segment.values);
536
666
  const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
537
667
  const rows = this.db.prepare(`
538
- SELECT clips.*, ${SEGMENT_COLUMNS}
668
+ SELECT clips.*, ${CLIP_TAGS_COLUMN}, ${SEGMENT_COLUMNS}
539
669
  FROM segments JOIN clips USING (clip_key)
540
670
  ${where}
541
671
  ORDER BY segments.smoothness DESC, segments.clip_key ASC, segments.start_sec ASC
542
672
  `).all(...values);
673
+ const decoded = rows.map((row) => ({ row, clip: decodeTaggedClip(row) }));
674
+ const matchesViewport = filters.bbox === undefined
675
+ ? undefined
676
+ : this.viewportMatcher(filters.bbox, decoded.map(({ clip }) => clip));
543
677
  const viewportCache = new Map();
544
678
  const results = [];
545
- for (const row of rows) {
546
- const clip = decodeClip(row);
547
- if (filters.bbox !== undefined) {
679
+ for (const { row, clip } of decoded) {
680
+ if (matchesViewport !== undefined) {
548
681
  let matches = viewportCache.get(clip.key);
549
682
  if (matches === undefined) {
550
- matches = this.clipMatchesViewport(filters.bbox, clip.key, clip.record);
683
+ matches = matchesViewport(clip);
551
684
  viewportCache.set(clip.key, matches);
552
685
  }
553
686
  if (!matches)
@@ -560,7 +693,7 @@ export class ArchiveStore {
560
693
  }
561
694
  commit(expectedRevision, updates, online, offline, removed) {
562
695
  this.transaction('BEGIN IMMEDIATE', () => {
563
- if (this.revision() !== expectedRevision) {
696
+ if (this.currentIndexRevision() !== expectedRevision) {
564
697
  throw new Error('archive index changed during scan, rerun the scan');
565
698
  }
566
699
  for (const update of updates)
@@ -574,9 +707,9 @@ export class ArchiveStore {
574
707
  for (const key of removed)
575
708
  remove.run(key);
576
709
  if (updates.length + removed.length > 0)
577
- this.refreshFlights();
710
+ this.refreshFlights([...updates.map(({ key }) => key), ...removed]);
578
711
  if (updates.length + online.length + offline.length + removed.length > 0) {
579
- this.db.exec('UPDATE archive_revision SET revision = revision + 1');
712
+ this.bumpIndexRevision();
580
713
  }
581
714
  });
582
715
  }
@@ -593,26 +726,27 @@ export class ArchiveStore {
593
726
  const remove = this.db.prepare('DELETE FROM clips WHERE clip_key = ?');
594
727
  for (const key of matched)
595
728
  remove.run(key);
596
- this.refreshFlights();
597
- this.db.exec('UPDATE archive_revision SET revision = revision + 1');
729
+ this.refreshFlights(matched);
730
+ this.bumpIndexRevision();
598
731
  return matched.length;
599
732
  });
600
733
  }
601
734
  pruneOffline() {
602
735
  return this.transaction('BEGIN IMMEDIATE', () => {
603
- const { changes } = this.db.prepare("DELETE FROM clips WHERE availability = 'offline'").run();
604
- const count = Number(changes);
736
+ const removed = this.db.prepare("DELETE FROM clips WHERE availability = 'offline' RETURNING clip_key")
737
+ .all();
738
+ const count = removed.length;
605
739
  if (count === 0)
606
740
  return 0;
607
- this.refreshFlights();
608
- this.db.exec('UPDATE archive_revision SET revision = revision + 1');
741
+ this.refreshFlights(removed.map(({ clip_key }) => clip_key));
742
+ this.bumpIndexRevision();
609
743
  return count;
610
744
  });
611
745
  }
612
- revision() {
613
- return this.db.prepare('SELECT revision FROM archive_revision').get()?.revision;
746
+ bumpIndexRevision() {
747
+ this.db.exec('UPDATE archive_revision SET revision = revision + 1, index_revision = index_revision + 1');
614
748
  }
615
- clipFilterClauses(bbox, availability, includeArcs, segmentFilter) {
749
+ clipFilterClauses(bbox, availability, includeArcs, segmentFilter, tags) {
616
750
  const clauses = [];
617
751
  const values = [];
618
752
  if (availability !== undefined) {
@@ -644,10 +778,15 @@ export class ArchiveStore {
644
778
  clauses.push(`EXISTS (SELECT 1 FROM segments WHERE ${segmentClauses.join(' AND ')})`);
645
779
  values.push(...segment.values);
646
780
  }
781
+ const filter = clipTagFilter(tags);
782
+ if (filter.clause) {
783
+ clauses.push(filter.clause);
784
+ values.push(...filter.values);
785
+ }
647
786
  return { clauses, values };
648
787
  }
649
- selectClips(bbox, availability, includeArcs, segmentFilter, overviewOnly = false) {
650
- const { clauses, values } = this.clipFilterClauses(bbox, availability, includeArcs, segmentFilter);
788
+ selectClips(bbox, availability, includeArcs, segmentFilter, overviewOnly = false, tags) {
789
+ const { clauses, values } = this.clipFilterClauses(bbox, availability, includeArcs, segmentFilter, tags);
651
790
  const where = clauses.length > 0 ? `WHERE ${clauses.join(' AND ')}` : '';
652
791
  const columns = overviewOnly
653
792
  ? `clips.clip_key, clips.availability, clips.size, clips.mtime_ms, clips.srt_size, clips.srt_mtime_ms,
@@ -655,7 +794,7 @@ export class ArchiveStore {
655
794
  clips.overview_json, clip_flights.flight_id, clip_flights.flight_order, clip_flights.split_from_key`
656
795
  : '*';
657
796
  const rows = this.db.prepare(`
658
- SELECT ${columns} FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
797
+ SELECT ${columns}, ${CLIP_TAGS_COLUMN} FROM clips JOIN clip_flights USING (clip_key) ${where} ORDER BY clip_key
659
798
  `).all(...values);
660
799
  return overviewOnly
661
800
  ? rows.map(decodeClipOverview)
@@ -671,31 +810,68 @@ export class ArchiveStore {
671
810
  `).all(JSON.stringify(flightIds));
672
811
  return new Map(rows.map(({ flight_id, camera_time }) => [flight_id, camera_time]));
673
812
  }
674
- refreshFlights() {
813
+ /** Regroup the streams that hold `changedKeys` (every clip when omitted); other memberships cannot change. */
814
+ refreshFlights(changedKeys) {
815
+ const keys = changedKeys === undefined ? undefined : this.clipKeysInDirectories(changedKeys);
816
+ if (keys?.length === 0)
817
+ return;
818
+ const filter = keys === undefined ? '' : 'WHERE clip_key IN (SELECT value FROM json_each(?))';
819
+ const params = keys === undefined ? [] : [JSON.stringify(keys)];
675
820
  const rows = this.db.prepare(`
676
- SELECT clip_key, size, json_extract(record_json, '$.cameraCreationTime') AS camera_time,
677
- json_extract(record_json, '$.video.durationSec') AS duration_sec
678
- FROM clips ORDER BY clip_key
679
- `).all();
680
- const first = this.db.prepare(`
681
- SELECT lat, lon, t_sec AS tSec FROM clip_samples
682
- WHERE clip_key = ? ORDER BY segment, sample_index LIMIT 1
683
- `);
684
- const last = this.db.prepare(`
685
- SELECT lat, lon, t_sec AS tSec FROM clip_samples
686
- WHERE clip_key = ? ORDER BY segment DESC, sample_index DESC LIMIT 1
687
- `);
688
- const memberships = groupFlights(rows.map(({ clip_key, size, camera_time, duration_sec }) => ({
689
- key: clip_key, size, startMs: camera_time === null ? null : zonedTimeMs(camera_time),
690
- durationSec: duration_sec,
691
- firstFix: first.get(clip_key),
692
- lastFix: last.get(clip_key),
821
+ SELECT clip.clip_key, clip.size, clip.camera_time, clip.duration_sec,
822
+ first_fix.lat AS first_lat, first_fix.lon AS first_lon, first_fix.t_sec AS first_t_sec,
823
+ last_fix.lat AS last_lat, last_fix.lon AS last_lon, last_fix.t_sec AS last_t_sec
824
+ FROM (
825
+ SELECT clip_key, size,
826
+ json_extract(record_json, '$.cameraCreationTime') AS camera_time,
827
+ json_extract(record_json, '$.video.durationSec') AS duration_sec,
828
+ (SELECT rowid FROM clip_samples WHERE clip_samples.clip_key = clips.clip_key
829
+ ORDER BY segment, sample_index LIMIT 1) AS first_id,
830
+ (SELECT rowid FROM clip_samples WHERE clip_samples.clip_key = clips.clip_key
831
+ ORDER BY segment DESC, sample_index DESC LIMIT 1) AS last_id
832
+ FROM clips ${filter}
833
+ ) AS clip
834
+ LEFT JOIN clip_samples AS first_fix ON first_fix.rowid = clip.first_id
835
+ LEFT JOIN clip_samples AS last_fix ON last_fix.rowid = clip.last_id
836
+ ORDER BY clip.clip_key
837
+ `).all(...params);
838
+ const memberships = groupFlights(rows.map((row) => ({
839
+ key: row.clip_key, size: row.size,
840
+ startMs: row.camera_time === null ? null : zonedTimeMs(row.camera_time),
841
+ durationSec: row.duration_sec,
842
+ firstFix: row.first_lat === null ? undefined : { lat: row.first_lat, lon: row.first_lon, tSec: row.first_t_sec },
843
+ lastFix: row.last_lat === null ? undefined : { lat: row.last_lat, lon: row.last_lon, tSec: row.last_t_sec },
693
844
  })));
694
- this.db.exec('DELETE FROM clip_flights');
845
+ if (keys === undefined)
846
+ this.db.exec('DELETE FROM clip_flights');
847
+ else
848
+ this.db.prepare('DELETE FROM clip_flights WHERE clip_key IN (SELECT value FROM json_each(?))').run(params[0]);
695
849
  const add = this.db.prepare('INSERT INTO clip_flights VALUES (?, ?, ?, ?)');
696
850
  for (const { key, flightId, order, splitFromKey } of memberships)
697
851
  add.run(key, flightId, order, splitFromKey);
698
852
  }
853
+ /** Flight streams never span directories (`groupFlights` partitions by `path.dirname`). */
854
+ clipKeysInDirectories(changedKeys) {
855
+ const directories = new Set(changedKeys.map((key) => path.dirname(key)));
856
+ const bounds = [...directories].map((directory) => [directory, prefixUpperBound(directory)]);
857
+ // Bare and `./` keys share the `.` directory without sharing a key prefix.
858
+ const scanAll = directories.has('.') || changedKeys.some((key) => !key.startsWith(path.dirname(key))) ||
859
+ bounds.some(([, upper]) => upper === null);
860
+ const candidates = scanAll
861
+ ? this.db.prepare('SELECT clip_key FROM clips').all()
862
+ : bounds.flatMap(([lower, upper]) => this.statement('SELECT clip_key FROM clips WHERE clip_key >= ? AND clip_key < ?').all(lower, upper));
863
+ return [...new Set(candidates.map(({ clip_key }) => clip_key))]
864
+ .filter((key) => directories.has(path.dirname(key)))
865
+ .sort();
866
+ }
867
+ statement(sql) {
868
+ let statement = this.statements.get(sql);
869
+ if (!statement) {
870
+ statement = this.db.prepare(sql);
871
+ this.statements.set(sql, statement);
872
+ }
873
+ return statement;
874
+ }
699
875
  transaction(begin, body) {
700
876
  this.db.exec(begin);
701
877
  try {
@@ -712,7 +888,7 @@ export class ArchiveStore {
712
888
  const { size, mtimeMs, srtSize, srtMtimeMs, schemaVersion } = fingerprint;
713
889
  const bbox = record.bbox;
714
890
  const segmentsIndexed = segments !== undefined ? 1 : 0;
715
- this.db.prepare(`
891
+ this.statement(`
716
892
  INSERT INTO clips (
717
893
  clip_key, availability, size, mtime_ms, srt_size, srt_mtime_ms, schema_version,
718
894
  min_lat, min_lon, max_lat, max_lon, record_json, overview_json, segments_indexed
@@ -727,26 +903,26 @@ export class ArchiveStore {
727
903
  record_json = excluded.record_json, overview_json = excluded.overview_json,
728
904
  segments_indexed = excluded.segments_indexed
729
905
  `).run(key, availability, size, mtimeMs, srtSize, srtMtimeMs, schemaVersion, bbox?.minLat ?? null, bbox?.minLon ?? null, bbox?.maxLat ?? null, bbox?.maxLon ?? null, JSON.stringify(record), JSON.stringify(overview), segmentsIndexed);
730
- this.db.prepare('DELETE FROM clip_samples WHERE clip_key = ?').run(key);
906
+ this.statement('DELETE FROM clip_samples WHERE clip_key = ?').run(key);
731
907
  this.writeGaze(key, gaze);
732
908
  this.writeSegments(key, segments);
733
- const add = this.db.prepare('INSERT INTO clip_samples VALUES (?, ?, ?, ?, ?, ?)');
909
+ const add = this.statement('INSERT INTO clip_samples VALUES (?, ?, ?, ?, ?, ?)');
734
910
  for (const [index, sample] of samples.entries()) {
735
911
  add.run(key, sample.segment, index, sample.tSec, sample.lat, sample.lon);
736
912
  }
737
913
  }
738
914
  writeGaze(key, gaze) {
739
- this.db.prepare('DELETE FROM clip_gaze WHERE clip_key = ?').run(key);
915
+ this.statement('DELETE FROM clip_gaze WHERE clip_key = ?').run(key);
740
916
  if (!gaze)
741
917
  return;
742
918
  const bbox = gazeBbox(gaze);
743
- this.db.prepare('INSERT INTO clip_gaze VALUES (?, ?, ?, ?, ?, ?)').run(key, bbox?.minLat ?? null, bbox?.maxLat ?? null, bbox?.minLon ?? null, bbox?.maxLon ?? null, JSON.stringify(gaze));
919
+ this.statement('INSERT INTO clip_gaze VALUES (?, ?, ?, ?, ?, ?)').run(key, bbox?.minLat ?? null, bbox?.maxLat ?? null, bbox?.minLon ?? null, bbox?.maxLon ?? null, JSON.stringify(gaze));
744
920
  }
745
921
  writeSegments(key, segments) {
746
- this.db.prepare('DELETE FROM segments WHERE clip_key = ?').run(key);
922
+ this.statement('DELETE FROM segments WHERE clip_key = ?').run(key);
747
923
  if (!segments)
748
924
  return;
749
- const add = this.db.prepare(`
925
+ const add = this.statement(`
750
926
  INSERT INTO segments (
751
927
  clip_key, segment_index, segment_type, start_sec, end_sec, duration_sec,
752
928
  smoothness, exposure_stable, mean_speed_mps, mean_yaw_rate_deg_per_sec
package/dist/tags.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export declare const MAX_ARCHIVE_TAG_LENGTH = 64;
2
+ export declare function archiveTagKey(tag: string): string;
3
+ export declare function parseArchiveTags(inputs: readonly string[]): string[];
package/dist/tags.js ADDED
@@ -0,0 +1,18 @@
1
+ export const MAX_ARCHIVE_TAG_LENGTH = 64;
2
+ const NON_PRINTABLE = /[\p{C}\p{Zl}\p{Zp}]/u;
3
+ export function archiveTagKey(tag) {
4
+ return tag.trim().toLowerCase().normalize('NFC');
5
+ }
6
+ export function parseArchiveTags(inputs) {
7
+ return inputs.flatMap((input) => input.split(',').map((part) => {
8
+ if (NON_PRINTABLE.test(part))
9
+ throw new Error('expected a tag with only printable characters');
10
+ const tag = part.trim();
11
+ if (!tag)
12
+ throw new Error('expected a nonempty tag');
13
+ if ([...tag].length > MAX_ARCHIVE_TAG_LENGTH) {
14
+ throw new Error(`expected a tag of at most ${MAX_ARCHIVE_TAG_LENGTH} characters`);
15
+ }
16
+ return tag;
17
+ }));
18
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-archive",
3
- "version": "2.0.1",
3
+ "version": "2.2.0",
4
4
  "description": "Scan a local library of drone recordings.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -40,7 +40,7 @@
40
40
  "directory": "packages/archive"
41
41
  },
42
42
  "dependencies": {
43
- "drone-path-core": "^2.0.1",
43
+ "drone-path-core": "^2.2.0",
44
44
  "leaflet": "^1.9.4",
45
45
  "p-queue": "^10.0.0"
46
46
  }