Skip to content

High performance self-hosted photo and video management solution.

13.0 KB
Raw Blame
import type { AssetMultiSelectManager } from '#lib/managers/asset-multi-select-manager.svelte.ts';
import { authManager } from '#lib/managers/auth-manager.svelte.ts';
import { downloadManager } from '#lib/managers/download-manager.svelte.ts';
import { eventManager } from '#lib/managers/event-manager.svelte.ts';
import { TimelineManager } from '#lib/managers/timeline-manager/timeline-manager.svelte.ts';
import type { TimelineAsset } from '#lib/managers/timeline-manager/types.ts';
import { locale } from '#lib/stores/preferences.store.ts';
import { downloadUrlPost, withError } from '#lib/utils.ts';
import { getByteUnitString } from '#lib/utils/byte-units.ts';
import { getFormatter } from '#lib/utils/i18n.ts';
import { navigate } from '#lib/utils/navigation.ts';
import { asQueryString } from '#lib/utils/shared-links.ts';
import { toTimelineAsset } from '#lib/utils/timeline-util.ts';
import {
  AssetVisibility,
  getBaseUrl,
  getDownloadInfo,
  untagAssets,
  updateAsset,
  updateAssets,
  type AssetResponseDto,
  type DownloadInfoDto,
  type ExifResponseDto,
  type UserResponseDto,
} from '@immich/sdk';
import { toastManager } from '@immich/ui';
import { DateTime } from 'luxon';
import { t } from 'svelte-i18n';
import { get } from 'svelte/store';
import { handleError } from './handle-error';

export const removeTag = async ({
  assetIds,
  tagIds,
  showNotification = true,
}: {
  assetIds: string[];
  tagIds: string[];
  showNotification?: boolean;
}) => {
  for (const tagId of tagIds) {
    await untagAssets({ id: tagId, bulkIdsDto: { ids: assetIds } });
  }

  if (showNotification) {
    const $t = await getFormatter();
    toastManager.primary($t('removed_tagged_assets', { values: { count: assetIds.length } }));
  }

  return assetIds;
};

export const downloadArchive = async (fileName: string, options: Omit<DownloadInfoDto, 'archiveSize'>) => {
  const archiveSize = authManager.authenticated ? authManager.preferences.download.archiveSize : undefined;
  const dto = { ...options, archiveSize };
  const [error, downloadInfo] = await withError(() => getDownloadInfo({ ...authManager.params, downloadInfoDto: dto }));
  if (error) {
    const $t = get(t);
    handleError(error, $t('errors.unable_to_download_files'));
    return;
  }

  if (!downloadInfo) {
    return;
  }

  for (let index = 0; index < downloadInfo.archives.length; index++) {
    const archive = downloadInfo.archives[index];
    const suffix = downloadInfo.archives.length > 1 ? `+${index + 1}` : '';
    const archiveName = `${fileName}${suffix}-${DateTime.now().toFormat('yyyyLLdd_HHmmss')}`;
    const queryParams = asQueryString(authManager.params);

    const downloadKey =
      downloadInfo.archives.length > 1
        ? `${archiveName} (${index + 1}/${downloadInfo.archives.length})`
        : `${archiveName} `;

    const url = getBaseUrl() + '/download/archive' + (queryParams ? `?${queryParams}` : '');

    try {
      if (downloadInfo.archives.length > 1) {
        downloadManager.add(downloadKey, url, archive.assetIds, archiveName, archive.size);
      } else {
        downloadUrlPost(url, archive.assetIds, archiveName);
        const $t = await getFormatter();
        const $locale = get(locale);
        toastManager.primary(
          $t('downloading_archive_filename_size', {
            values: { size: getByteUnitString(archive.size, $locale), filename: archiveName },
          }),
          { timeout: 10_000 },
        );
      }
    } catch (error) {
      const $t = get(t);
      handleError(error, $t('errors.unable_to_download_files'));
      return;
    }
  }
};

/**
Returns the lowercase filename extension without a dot (.) and
an empty string when not found.
*/
export function getFilenameExtension(filename: string): string {
  const lastIndex = Math.max(0, filename.lastIndexOf('.'));
  const startIndex = (lastIndex || Infinity) + 1;
  return filename.slice(startIndex).toLowerCase();
}

/** Returns the filename of an asset including file extension */
export function getAssetFilename(asset: AssetResponseDto): string {
  const fileExtension = getFilenameExtension(asset.originalPath);
  return `${asset.originalFileName}.${fileExtension}`;
}

function isRotated90CW(orientation: number) {
  return [5, 6, 90].includes(orientation);
}

function isRotated270CW(orientation: number) {
  return [7, 8, -90].includes(orientation);
}

function isFlipped(orientation?: string | null) {
  const value = Number(orientation);
  return value && (isRotated270CW(value) || isRotated90CW(value));
}

export const getDimensions = (exifInfo: ExifResponseDto) => {
  const { exifImageWidth: width, exifImageHeight: height } = exifInfo;
  if (isFlipped(exifInfo.orientation)) {
    return { width: height, height: width };
  }

  return { width, height };
};

export function getFileSize(asset: AssetResponseDto, maxPrecision = 4): string {
  const size = asset.exifInfo?.fileSizeInByte || 0;
  return size > 0 ? getByteUnitString(size, undefined, maxPrecision) : 'Invalid Data';
}

export function getAssetResolution(asset: AssetResponseDto): string {
  if (!asset.width || !asset.height) {
    return 'Invalid Data';
  }

  return `${asset.width} × ${asset.height}`;
}

/** Returns aspect ratio for the asset */
export function getAssetRatio(asset: AssetResponseDto) {
  return asset.width && asset.height ? asset.width / asset.height : null;
}

// list of supported image extensions from https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types excluding svg
const supportedImageMimeTypes = new Set([
  'image/apng',
  'image/avif',
  'image/bmp',
  'image/gif',
  'image/jpeg',
  'image/png',
  'image/webp',
]);

export const isFirefox = typeof navigator !== 'undefined' && navigator.userAgent.includes('Firefox');

async function addSupportedMimeTypes(): Promise<void> {
  const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); // https://stackoverflow.com/a/23522755
  if (isSafari) {
    const match = navigator.userAgent.match(/Version\/(\d+)/);

    if (!match) {
      return;
    }

    const majorVersion = Number.parseInt(match[1]);
    const MIN_REQUIRED_VERSION = 17;

    if (majorVersion >= MIN_REQUIRED_VERSION) {
      supportedImageMimeTypes.add('image/jxl').add('image/heic').add('image/heif');
    }

    return;
  }

  if (globalThis.isSecureContext && typeof ImageDecoder !== 'undefined') {
    const dynamicMimeTypes = [{ type: 'image/jxl' }, { type: 'image/heic', aliases: ['image/heif'] }];

    for (const mime of dynamicMimeTypes) {
      const isMimeTypeSupported = await ImageDecoder.isTypeSupported(mime.type);
      if (isMimeTypeSupported) {
        for (const mimeType of [mime.type, ...(mime.aliases || [])]) {
          supportedImageMimeTypes.add(mimeType);
        }
      }
    }

    return;
  }

  const jxlImg = new Image();
  jxlImg.addEventListener('load', () => {
    supportedImageMimeTypes.add('image/jxl');
  });
  jxlImg.src = 'data:image/jxl;base64,/woIAAAMABKIAgC4AF3lEgA='; // Small valid JPEG XL image

  const heicImg = new Image();
  heicImg.addEventListener('load', () => {
    supportedImageMimeTypes.add('image/heic');
  });
  heicImg.src =
    'data:image/heic;base64,AAAAGGZ0eXBoZWljAAAAAG1pZjFoZWljAAABrW1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAHBpY3QAAAAAAAAAAAAAAAAAAAAADnBpdG0AAAAAAAIAAAAQaWRhdAAAAAAAAQABAAAAOGlsb2MBAAAAREAAAgABAAAAAAAAAc0AAQAAAAAAAAAsAAIAAQAAAAAAAAABAAAAAAAAAAgAAAA4aWluZgAAAAAAAgAAABVpbmZlAgAAAQABAABodmMxAAAAABVpbmZlAgAAAAACAABncmlkAAAAANhpcHJwAAAAtmlwY28AAAB2aHZjQwEDcAAAAAAAAAAAAB7wAPz9+PgAAA8DIAABABhAAQwB//8DcAAAAwCQAAADAAADAB66AkAhAAEAKkIBAQNwAAADAJAAAAMAAAMAHqAggQWW6q6a5uBAQMCAAAADAIAAAAMAhCIAAQAGRAHBc8GJAAAAFGlzcGUAAAAAAAAAAQAAAAEAAAAUaXNwZQAAAAAAAABAAAAAQAAAABBwaXhpAAAAAAMICAgAAAAaaXBtYQAAAAAAAAACAAECgQMAAgIChAAAABppcmVmAAAAAAAAAA5kaW1nAAIAAQABAAAANG1kYXQAAAAoKAGvCchMZYA50NoPIfzz81Qfsm577GJt3lf8kLAr+NbNIoeRR7JeYA=='; // Small valid HEIC/HEIF image
}
// eslint-disable-next-line unicorn/no-top-level-side-effects
void addSupportedMimeTypes();

/** Returns true if the asset is an image supported by web browsers, false otherwise */
export function isWebCompatibleImage(asset: AssetResponseDto): boolean {
  if (!asset.originalMimeType) {
    return false;
  }

  return supportedImageMimeTypes.has(asset.originalMimeType);
}

export const getOwnedAssetsWithWarning = (assets: TimelineAsset[], user: UserResponseDto | null): string[] => {
  const ids = [...assets].filter((a) => user && a.ownerId === user.id).map((a) => a.id);

  const numberOfIssues = [...assets].filter((a) => user && a.ownerId !== user.id).length;
  if (numberOfIssues > 0) {
    const $t = get(t);
    toastManager.warning($t('errors.cant_change_metadata_assets_count', { values: { count: numberOfIssues } }));
  }
  return ids;
};

export const selectAllAssets = async (timelineManager: TimelineManager, assetInteraction: AssetMultiSelectManager) => {
  if (assetInteraction.selectAll) {
    // Selection is already ongoing
    return;
  }
  assetInteraction.selectAll = true;

  try {
    for (const timelineMonth of timelineManager.months) {
      if (!timelineMonth.isLoaded) {
        await timelineManager.loadTimelineMonth(timelineMonth.yearMonth);
      }

      if (!assetInteraction.selectAll) {
        assetInteraction.clear();
        break; // Cancelled
      }
      assetInteraction.selectAssets([...timelineMonth.assetsIterator()]);

      for (const dateGroup of timelineMonth.timelineDays) {
        assetInteraction.addGroupToMultiselectGroup(dateGroup.groupTitle);
      }
    }
  } catch (error) {
    const $t = get(t);
    handleError(error, $t('errors.error_selecting_all_assets'));
    assetInteraction.selectAll = false;
  }
};

export const toggleArchive = async (asset: AssetResponseDto) => {
  const $t = get(t);
  try {
    const data = await updateAsset({
      id: asset.id,
      updateAssetDto: {
        visibility: asset.isArchived ? AssetVisibility.Timeline : AssetVisibility.Archive,
      },
    });

    asset.isArchived = data.isArchived;
    asset.visibility = data.visibility;
    if (asset.isArchived) {
      const timelineAsset = toTimelineAsset(asset);
      showUndoArchiveToast($t('added_to_archive'), [timelineAsset]);
    } else {
      toastManager.primary($t('removed_from_archive'));
    }
  } catch (error) {
    handleError(error, $t('errors.unable_to_add_remove_archive', { values: { archived: asset.isArchived } }));
  }

  return asset;
};

const showUndoArchiveToast = (description: string, assets: TimelineAsset[]) => {
  const $t = get(t);
  toastManager.primary({
    description,
    button: (close) => ({
      label: $t('undo'),
      onclick: () => {
        close();
        void undoArchiveAssets(assets);
      },
    }),
  });
};

const undoArchiveAssets = async (assets: TimelineAsset[]) => {
  const $t = get(t);
  try {
    const ids = assets.map((a) => a.id);
    if (ids.length > 0) {
      await updateAssets({
        assetBulkUpdateDto: {
          ids,
          visibility: AssetVisibility.Timeline,
        },
      });
    }

    for (const asset of assets) {
      asset.visibility = AssetVisibility.Timeline;
    }
    eventManager.emit('AssetsUnarchive', assets);
    eventManager.emit('AssetsUndoArchive', assets);
    toastManager.success($t('unarchived_count', { values: { count: assets.length } }));
  } catch (error) {
    handleError(error, $t('errors.unable_to_archive_unarchive', { values: { archived: false } }));
  }
};

export const delay = async (ms: number) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

export const getNextAsset = (assets: AssetResponseDto[], currentAsset: AssetResponseDto | undefined) => {
  const index = currentAsset ? assets.findIndex((a) => a.id === currentAsset.id) : -1;
  return index >= 0 ? assets[index + 1] : undefined;
};

export const getPreviousAsset = (assets: AssetResponseDto[], currentAsset: AssetResponseDto | undefined) => {
  const index = currentAsset ? assets.findIndex((a) => a.id === currentAsset.id) : -1;
  return index >= 0 ? assets[index - 1] : undefined;
};

export const canCopyImageToClipboard = (): boolean => {
  return !!(navigator.clipboard && globalThis.ClipboardItem);
};

const imgToBlob = async (imageElement: HTMLImageElement) => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');

  canvas.width = imageElement.naturalWidth;
  canvas.height = imageElement.naturalHeight;

  if (context) {
    context.drawImage(imageElement, 0, 0);

    return await new Promise<Blob>((resolve) => {
      canvas.toBlob((blob) => {
        if (blob) {
          resolve(blob);
        } else {
          throw new Error('Canvas conversion to Blob failed');
        }
      });
    });
  }

  throw new Error('Canvas context is null');
};

export const copyImageToClipboard = async (source: HTMLImageElement) => {
  // do not await, so the Safari clipboard write happens in the context of the user gesture
  await navigator.clipboard.write([new ClipboardItem({ ['image/png']: imgToBlob(source) })]);
};

export const navigateToAsset = async (targetAsset: AssetResponseDto | undefined | null) => {
  if (!targetAsset) {
    return false;
  }

  await navigate({ targetRoute: 'current', assetId: targetAsset.id });
  return true;
};