Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
7.7 KB
Raw Blame
/**
 * Free-text search + sorting for the Media Library grid. Pure functions so a
 * case with hundreds of items stays navigable and the behavior stays testable.
 */
import { foldTerms, foldText } from './textFold.js';

/** A match against everything the analyst might remember: filename, title, notes,
 *  folder, and the download's title/uploader/URL. Folded like the server's index
 *  (`store/rows._media_search_text`), so `cafe` finds `Café` on either side. */
export function matchesQuery(item, query) {
  const terms = foldTerms(query);
  if (!terms.length) return true;
  const haystack = foldText([
    item.filename,
    item.title,
    item.notes,
    item.folder,
    item.source?.title,
    item.source?.uploader,
    item.source?.webpage_url ?? item.source?.url,
  ]
    .filter(Boolean)
    .join('\n'));
  return terms.every((term) => haystack.includes(term));
}

/** True for native satellite captures and extension screenshots whose URL
 * explicitly identified satellite imagery. */
export function isSatelliteMedia(item) {
  const source = item?.source ?? {};
  return source.type === 'satellite' ||
    (source.type === 'screenshot' && source.imagery_mode === 'satellite');
}

/** A Compare render or a kept Detect finding: before/after pictures the app drew. */
export function isComparison(item) {
  return item?.source?.type === 'compare';
}

/** Images that are neither satellite captures nor comparisons, as the server's
 *  `image` facet counts them. */
export function isGenericImage(item) {
  return item?.kind === 'image' && !isSatelliteMedia(item) && !isComparison(item);
}

/** How material the analyst brought in by hand arrives: dropped or picked off a
 *  disk, or pasted out of the clipboard. Two source types and one facet — the
 *  filter asks who brought the file in, not which gesture did it. Mirrors
 *  `_MEDIA_CATEGORY_SQL['upload']`, which the server answers the same question with. */
const BROUGHT_IN = new Set(['upload', 'clipboard']);

/** Whether the analyst put this file into the case themselves. */
export function isBroughtIn(item) {
  return BROUGHT_IN.has(item?.source?.type);
}

/** The tools whose output the app produced rather than the analyst gathered. Mirrors
 *  `links.PRODUCED_HERE` — a wider set than the graph's `MADE_HERE`, and that file is
 *  where the two and the reason they differ by a capture are written down. The server
 *  filters on the same set, and this is the in-memory pass a case small enough for one
 *  page takes instead. */
const MADE_HERE = new Set(['inspect', 'satellite', 'screenshot', 'compare', 'horizon']);

/** Whether the app produced this file rather than the analyst gathering it: an
 *  extracted frame, an adjustment, a collage, a capture drawn out of tiles, a map
 *  the extension grabbed off the screen, a Compare render or a kept Detect finding,
 *  a picture of a saved Horizon view.
 *
 *  Reads **how the file entered the case**, not everything true about it. Bytes
 *  imported first and later found identical to a frame keep `upload`, because that
 *  is how they arrived — which is the same reason the graph reads the origin off
 *  the index rather than off the derivation links, where both are true at once. */
export function isMadeHere(item) {
  return MADE_HERE.has(item?.source?.type);
}

/** The type and source facets, shared by the Media Library's filter and the
 *  Satellite reference picker's chips. They overlap on purpose: a downloaded
 *  video is both a Video and a Download. Keys and order are the server's
 *  `_MEDIA_CATEGORIES`, and `_MEDIA_CATEGORY_SQL` counts the same facets. */
export const MEDIA_CATEGORIES = [
  { key: 'image', label: 'Images', icon: 'image', match: isGenericImage },
  { key: 'video', label: 'Videos', icon: 'video', match: (i) => i.kind === 'video' },
  { key: 'collage', label: 'Collages', icon: 'layers', match: (i) => i.source?.op === 'collage' },
  { key: 'satellite', label: 'Satellite', icon: 'satellite', match: isSatelliteMedia },
  { key: 'comparison', label: 'Comparisons', icon: 'compare', match: isComparison },
  { key: 'upload', label: 'Imports', icon: 'upload', match: isBroughtIn },
  { key: 'download', label: 'Downloads', icon: 'download', match: (i) => i.source?.type === 'download' },
  { key: 'other', label: 'Other files', icon: 'file', match: (i) => i.kind !== 'image' && i.kind !== 'video' },
];

/** User-facing kind label for the Media Library card. */
export function mediaDisplayKind(item) {
  return isSatelliteMedia(item) ? 'satellite' : item?.kind;
}

export const SORTS = [
  { id: 'newest', label: 'Newest first' },
  { id: 'oldest', label: 'Oldest first' },
  { id: 'name', label: 'Name A–Z' },
  { id: 'size', label: 'Largest first' },
];

/**
 * The media rows the grid should render: filtered by category/folder/query and
 * sorted. Returns nothing when no case is open — the cards read
 * `caseState.current.id` for their file URLs, so rendering a stale list while
 * the case is being closed (a brief window where `current` is null but `items`
 * hasn't been cleared yet) would throw and abort the whole reactive flush,
 * leaving *other* tools un-reset. Gating on `hasCase` makes that impossible
 * regardless of effect ordering.
 */
export function visibleMedia(
  items,
  {
    hasCase = true,
    catMatch = null,
    folderFilter = null,
    gpsOnly = false,
    collectedOnly = false,
    query = '',
    sort = 'newest',
    direction,
  } = {}
) {
  if (!hasCase) return [];
  return sortItems(
    items.filter(
      (i) =>
        (!catMatch || catMatch(i)) &&
        (!folderFilter || i.folder === folderFilter) &&
        (!gpsOnly || hasPosition(i)) &&
        (!collectedOnly || !isMadeHere(i)) &&
        matchesQuery(i, query)
    ),
    sort,
    direction
  );
}

/** The position a file's own metadata states, or null. Enrichment writes it from
 *  image EXIF or a video's container tags; both land on the same field. */
export function mediaPoint(item) {
  const lat = Number(item?.gps?.lat);
  const lon = Number(item?.gps?.lon);
  if (!Number.isFinite(lat) || !Number.isFinite(lon)) return null;
  return { lat, lon };
}

export function hasPosition(item) {
  return mediaPoint(item) !== null;
}

/** Whether a folder and category can produce at least one media item.
 *  Deliberately ignores the text query: choosing a compatible folder/type
 *  combination should not reset either filter just because a search is active.
 */
export function hasMediaForFilters(items, { catMatch = null, folderFilter = null } = {}) {
  return items.some(
    (i) => (!catMatch || catMatch(i)) && (!folderFilter || i.folder === folderFilter)
  );
}

const displayName = (i) => (i.title ?? i.filename ?? '').toLowerCase();

/** Stable-sorted copy of `items` (the API's order is newest-first on disk scan,
 *  but sorting explicitly keeps the toggle honest whatever the backend does). */
export function sortItems(items, sort, direction) {
  const out = [...items];
  let descending = false;
  switch (sort) {
    case 'oldest':
      out.sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? ''));
      break;
    case 'name':
      out.sort((a, b) => displayName(a).localeCompare(displayName(b)));
      break;
    case 'type':
      out.sort((a, b) => (mediaDisplayKind(a) ?? '').localeCompare(mediaDisplayKind(b) ?? ''));
      break;
    case 'folder':
      out.sort((a, b) => (a.folder ?? '').localeCompare(b.folder ?? ''));
      break;
    case 'size':
      out.sort((a, b) => (a.size ?? 0) - (b.size ?? 0));
      descending = true;
      break;
    case 'newest':
    default:
      out.sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? ''));
      descending = true;
      break;
  }
  if (direction === 'asc') descending = false;
  if (direction === 'desc') descending = true;
  if (descending) out.reverse();
  return out;
}