1
0
mirror of https://github.com/immich-app/immich.git synced 2025-06-08 02:36:22 +02:00
immich/web/src/lib/utils/file-uploader.ts

203 lines
5.6 KiB
TypeScript
Raw Normal View History

import {
notificationController,
NotificationType
} from './../components/shared-components/notification/notification';
import { uploadAssetsStore } from '$lib/stores/upload';
import type { UploadAsset } from '../models/upload-asset';
import { api, AssetFileUploadResponseDto } from '@api';
import { addAssetsToAlbum, getFileMimeType, getFilenameExtension } from '$lib/utils/asset-utils';
import { Subject, mergeMap } from 'rxjs';
export const openFileUploadDialog = (
albumId: string | undefined = undefined,
sharedKey: string | undefined = undefined,
onDone?: (id: string) => void
) => {
try {
2022-09-08 17:30:49 +02:00
const fileSelector = document.createElement('input');
fileSelector.type = 'file';
fileSelector.multiple = true;
// When adding a content type that is unsupported by browsers, make sure
// to also add it to getFileMimeType() otherwise the upload will fail.
feat(server/web): Initial support for RAF and SRW RAW formats (#1414) * feat(server/web): Initial support for RAF and SRW RAW formats. * It should return the promise. * Better comment * feat(server/web): file-uploader needed changes. * Remove un-used imports * The failing test.. is no longer failing. * Run prettier * Original implementation with just a catch block added. * feat(server): Some tests and specific handling for the two raw formats * feat(web): Helper for raw image type. * Handling of mimetype on server * Handling of mimetypes on web with a map * Bring back the acceptedfile filter * Fix the asset-upload tests after changes * acceptedFile is not usable due to type being empty from browser. * Switch needs to use lowercase variants. * Address Discord comments * feat(mobile): Library page rework (album sorting, favorites) (#1501) * Add album sorting * Change AppBar to match photos page behaviour * Add buttons * First crude implementation of the favorites page * Clean up * Add favorite button * i18n * Add star indicator to thumbnail * Add favorite logic to separate provider and fix favorite behavior in album * Review feedback (Add isFavorite variable) * dev: style buttons * dev: styled drop down button --------- Co-authored-by: Alex Tran <alex.tran1502@gmail.com> * feat(mobile): Tap to enter immersive mode on gallery viewer (#1546) * feat(mobile): Removed stay logged in checkbox and made it enabled by default (#1550) * removed stay logged in checkbox and made it enabled by default * adds padding to login button * removed all isSaveLogin * fix: logout would re-login with previous credential upon app restart --------- Co-authored-by: Alex <alex.tran1502@gmail.com> * chore(server): remove token when logged out (#1560) * chore(mobile): invoke logout() on mobile app * feat: add mechanism to delete token from logging out endpoint * fix: set state after login sequence success * fix: not removing token when logging out from OAuth * fix: prettier * refactor: using accessTokenId to delete * chore: pr comments * fix: test * fix: test threshold * feat(deployment): support docker secrets (#1254) * Support secrets * Rewrite to support sh * Remove JWT_SECRET * fix(mobile): Added flutter native splash and splash screens (#1520) * rebasing * added launch background image to repository --------- Co-authored-by: Marty Fuhry <marty@fuhry.farm> * refactor(mobile): introduce Album & User classes (#1561) replace usages of AlbumResponseDto with Album replace usages of UserResponseDto with User * feat(mobile): Multiselect add to favorite from the timeline (#1558) * multiselect add to favorites * feat(server): add updatedAt to Asset, Album and User (#1566) * feat: add updatedAt info to DTO and generate api * chore: remove unsued file * chore: Add update statement to add/remove asset/user to album * fix: test * chore(server): update package-lock.json to match package.json (#1573) * chore(server) Add user FK to album entity (#1569) * chore(deps): bump docker/setup-buildx-action from 2.4.0 to 2.4.1 (#1575) Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2.4.0 to 2.4.1. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/v2.4.0...v2.4.1) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(server): make owner as required response for AlbumResponseDto (#1579) * feat(GitHub): update bug and feature request template (#1584) * dev: Reusing template from Home Assistant * dev: add bug report template * fix: template * dev: change type * dev: * dev: add default labels * dev: Add default title * dev: add feature request template * remove feature request from markdown * dev: frontmatter * fix(GitHub): feature request template * fix(GitHub): feature request form has wrong type for textarea * feat(mobile): Responsive layout improvements with a navigation rail and album grid (#1583) * feat(proxy): Initial IPv6 support (#1577) * fix(server): Create album response doesn't have owner property as required (#1704) * feat(web): allow uploading more file types (#1570) * feat(web): allow uploading more file types * fix(web): make filename extension lowercase * refactor(mobile): add Isar DB & Store class (#1574) * refactor(mobile): add Isar DB & Store class new Store: globally accessible key-value store like Hive (but based on Isar) replace first few places of Hive usage with the new Store * reduce max. DB size to prevent errors on older iOS devices --------- Co-authored-by: Alex <alex.tran1502@gmail.com> * feat(mobile): Home screen customization options (#1563) * Try staggered layout for home page * Introduce setting for dynamic layout * Fix some provider related bugs * Make asset grouping configurable * Add translation keys, refactor group title * Rename enum values * Fix enum names * Reformat long if statement * Fix timezone related bug * Minor clean up * Fix unit test * Add second assets check back to home screen * [Localizely] Translations update (#1707) * fix(server): get shared link album info doesn't contain owner property (#1708) * Version v1.46.0 * feat(server/web): file-uploader needed changes. * Add raf and srw to the file names. * Remember to add the extensions to fileSelector. * Removed the getMimeType function on server as shouldn't be needed anymore. * Revert "Removed the getMimeType function on server as shouldn't be needed anymore." It is required still. This reverts commit fc766dd0beeaa54eb27f73e4ec0bbe4913220fde. * Should use proper mimetypes. * fix linter --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Matthias Rupp <matthias.rupp@posteo.de> Co-authored-by: Alex Tran <alex.tran1502@gmail.com> Co-authored-by: martyfuhry <martyfuhry@gmail.com> Co-authored-by: James <jdm12989@gmail.com> Co-authored-by: Marty Fuhry <marty@fuhry.farm> Co-authored-by: Fynn Petersen-Frey <zoodyy@users.noreply.github.com> Co-authored-by: Zack Pollard <zackpollard@ymail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Michel Heusschen <59014050+michelheusschen@users.noreply.github.com> Co-authored-by: Immich Release Bot <bot@immich.app>
2023-02-14 21:54:28 +02:00
fileSelector.accept = 'image/*,video/*,.heic,.heif,.dng,.3gp,.nef,.srw,.raf';
2022-09-08 17:30:49 +02:00
fileSelector.onchange = async (e: Event) => {
const target = e.target as HTMLInputElement;
if (!target.files) {
return;
}
const files = Array.from<File>(target.files);
await fileUploadHandler(files, albumId, sharedKey, onDone);
};
fileSelector.click();
} catch (e) {
console.log('Error selecting file', e);
}
};
export const fileUploadHandler = async (
files: File[],
albumId: string | undefined = undefined,
sharedKey: string | undefined = undefined,
onDone?: (id: string) => void
) => {
const files$ = new Subject<File>();
files$
.pipe(
mergeMap(async (file) => {
await fileUploader(file, albumId, sharedKey, onDone);
}, 2)
)
.subscribe();
feat(server/web): Initial support for RAF and SRW RAW formats (#1414) * feat(server/web): Initial support for RAF and SRW RAW formats. * It should return the promise. * Better comment * feat(server/web): file-uploader needed changes. * Remove un-used imports * The failing test.. is no longer failing. * Run prettier * Original implementation with just a catch block added. * feat(server): Some tests and specific handling for the two raw formats * feat(web): Helper for raw image type. * Handling of mimetype on server * Handling of mimetypes on web with a map * Bring back the acceptedfile filter * Fix the asset-upload tests after changes * acceptedFile is not usable due to type being empty from browser. * Switch needs to use lowercase variants. * Address Discord comments * feat(mobile): Library page rework (album sorting, favorites) (#1501) * Add album sorting * Change AppBar to match photos page behaviour * Add buttons * First crude implementation of the favorites page * Clean up * Add favorite button * i18n * Add star indicator to thumbnail * Add favorite logic to separate provider and fix favorite behavior in album * Review feedback (Add isFavorite variable) * dev: style buttons * dev: styled drop down button --------- Co-authored-by: Alex Tran <alex.tran1502@gmail.com> * feat(mobile): Tap to enter immersive mode on gallery viewer (#1546) * feat(mobile): Removed stay logged in checkbox and made it enabled by default (#1550) * removed stay logged in checkbox and made it enabled by default * adds padding to login button * removed all isSaveLogin * fix: logout would re-login with previous credential upon app restart --------- Co-authored-by: Alex <alex.tran1502@gmail.com> * chore(server): remove token when logged out (#1560) * chore(mobile): invoke logout() on mobile app * feat: add mechanism to delete token from logging out endpoint * fix: set state after login sequence success * fix: not removing token when logging out from OAuth * fix: prettier * refactor: using accessTokenId to delete * chore: pr comments * fix: test * fix: test threshold * feat(deployment): support docker secrets (#1254) * Support secrets * Rewrite to support sh * Remove JWT_SECRET * fix(mobile): Added flutter native splash and splash screens (#1520) * rebasing * added launch background image to repository --------- Co-authored-by: Marty Fuhry <marty@fuhry.farm> * refactor(mobile): introduce Album & User classes (#1561) replace usages of AlbumResponseDto with Album replace usages of UserResponseDto with User * feat(mobile): Multiselect add to favorite from the timeline (#1558) * multiselect add to favorites * feat(server): add updatedAt to Asset, Album and User (#1566) * feat: add updatedAt info to DTO and generate api * chore: remove unsued file * chore: Add update statement to add/remove asset/user to album * fix: test * chore(server): update package-lock.json to match package.json (#1573) * chore(server) Add user FK to album entity (#1569) * chore(deps): bump docker/setup-buildx-action from 2.4.0 to 2.4.1 (#1575) Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2.4.0 to 2.4.1. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/v2.4.0...v2.4.1) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(server): make owner as required response for AlbumResponseDto (#1579) * feat(GitHub): update bug and feature request template (#1584) * dev: Reusing template from Home Assistant * dev: add bug report template * fix: template * dev: change type * dev: * dev: add default labels * dev: Add default title * dev: add feature request template * remove feature request from markdown * dev: frontmatter * fix(GitHub): feature request template * fix(GitHub): feature request form has wrong type for textarea * feat(mobile): Responsive layout improvements with a navigation rail and album grid (#1583) * feat(proxy): Initial IPv6 support (#1577) * fix(server): Create album response doesn't have owner property as required (#1704) * feat(web): allow uploading more file types (#1570) * feat(web): allow uploading more file types * fix(web): make filename extension lowercase * refactor(mobile): add Isar DB & Store class (#1574) * refactor(mobile): add Isar DB & Store class new Store: globally accessible key-value store like Hive (but based on Isar) replace first few places of Hive usage with the new Store * reduce max. DB size to prevent errors on older iOS devices --------- Co-authored-by: Alex <alex.tran1502@gmail.com> * feat(mobile): Home screen customization options (#1563) * Try staggered layout for home page * Introduce setting for dynamic layout * Fix some provider related bugs * Make asset grouping configurable * Add translation keys, refactor group title * Rename enum values * Fix enum names * Reformat long if statement * Fix timezone related bug * Minor clean up * Fix unit test * Add second assets check back to home screen * [Localizely] Translations update (#1707) * fix(server): get shared link album info doesn't contain owner property (#1708) * Version v1.46.0 * feat(server/web): file-uploader needed changes. * Add raf and srw to the file names. * Remember to add the extensions to fileSelector. * Removed the getMimeType function on server as shouldn't be needed anymore. * Revert "Removed the getMimeType function on server as shouldn't be needed anymore." It is required still. This reverts commit fc766dd0beeaa54eb27f73e4ec0bbe4913220fde. * Should use proper mimetypes. * fix linter --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Matthias Rupp <matthias.rupp@posteo.de> Co-authored-by: Alex Tran <alex.tran1502@gmail.com> Co-authored-by: martyfuhry <martyfuhry@gmail.com> Co-authored-by: James <jdm12989@gmail.com> Co-authored-by: Marty Fuhry <marty@fuhry.farm> Co-authored-by: Fynn Petersen-Frey <zoodyy@users.noreply.github.com> Co-authored-by: Zack Pollard <zackpollard@ymail.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Michel Heusschen <59014050+michelheusschen@users.noreply.github.com> Co-authored-by: Immich Release Bot <bot@immich.app>
2023-02-14 21:54:28 +02:00
const acceptedFile = files.filter((file) => {
const assetType = getFileMimeType(file).split('/')[0];
return assetType === 'video' || assetType === 'image';
});
for (const file of acceptedFile) {
files$.next(file);
}
};
2022-09-08 17:30:49 +02:00
//TODO: should probably use the @api SDK
async function fileUploader(
asset: File,
albumId: string | undefined = undefined,
sharedKey: string | undefined = undefined,
onDone?: (id: string) => void
) {
console.log('uploading', asset.name);
const mimeType = getFileMimeType(asset);
const assetType = mimeType.split('/')[0].toUpperCase();
const fileExtension = getFilenameExtension(asset.name);
const formData = new FormData();
const createdAt = new Date(asset.lastModified).toISOString();
const deviceAssetId = 'web' + '-' + asset.name + '-' + asset.lastModified;
try {
// Create and add Unique ID of asset on the device
formData.append('deviceAssetId', deviceAssetId);
// Get device id - for web -> use WEB
formData.append('deviceId', 'WEB');
// Get asset type
formData.append('assetType', assetType);
// Get Asset Created Date
formData.append('createdAt', createdAt);
// Get Asset Modified At
formData.append('modifiedAt', new Date(asset.lastModified).toISOString());
// Set Asset is Favorite to false
formData.append('isFavorite', 'false');
// Get asset duration
formData.append('duration', '0:00:00.000000');
// Get asset file extension
formData.append('fileExtension', '.' + fileExtension);
// Get asset binary data with a custom MIME type, because browsers will
// use application/octet-stream for unsupported MIME types, leading to
// failed uploads.
formData.append('assetData', new File([asset], asset.name, { type: mimeType }));
// Check if asset upload on server before performing upload
const { data, status } = await api.assetApi.checkDuplicateAsset(
{
deviceAssetId: String(deviceAssetId),
deviceId: 'WEB'
},
{
params: {
key: sharedKey
}
}
);
if (status === 200) {
if (data.isExist) {
2022-09-08 17:30:49 +02:00
const dataId = data.id;
if (albumId && dataId) {
addAssetsToAlbum(albumId, [dataId], sharedKey);
}
onDone && dataId && onDone(dataId);
return;
}
}
const request = new XMLHttpRequest();
request.upload.onloadstart = () => {
const newUploadAsset: UploadAsset = {
id: deviceAssetId,
file: asset,
progress: 0,
fileExtension: fileExtension
};
uploadAssetsStore.addNewUploadAsset(newUploadAsset);
};
2022-09-08 17:30:49 +02:00
request.upload.onload = () => {
uploadAssetsStore.removeUploadAsset(deviceAssetId);
const res: AssetFileUploadResponseDto = JSON.parse(request.response || '{}');
if (albumId) {
try {
if (res.id) {
addAssetsToAlbum(albumId, [res.id], sharedKey);
}
} catch (e) {
console.error('ERROR parsing data JSON in upload onload');
}
}
onDone && onDone(res.id);
};
// listen for `error` event
2022-09-08 17:30:49 +02:00
request.upload.onerror = () => {
uploadAssetsStore.removeUploadAsset(deviceAssetId);
handleUploadError(asset, request.response);
};
// listen for `abort` event
request.upload.onabort = () => {
uploadAssetsStore.removeUploadAsset(deviceAssetId);
handleUploadError(asset, request.response);
};
// listen for `progress` event
request.upload.onprogress = (event) => {
const percentComplete = Math.floor((event.loaded / event.total) * 100);
uploadAssetsStore.updateProgress(deviceAssetId, percentComplete);
};
request.open('POST', `/api/asset/upload?key=${sharedKey ?? ''}`);
request.send(formData);
} catch (e) {
console.log('error uploading file ', e);
}
}
function handleUploadError(asset: File, respBody = '{}', extraMessage?: string) {
try {
const res = JSON.parse(respBody);
const extraMsg = res ? ' ' + res?.message : '';
notificationController.show({
type: NotificationType.Error,
message: `Cannot upload file ${asset.name} ${extraMsg}${extraMessage}`,
timeout: 5000
});
} catch (e) {
console.error('ERROR parsing data JSON in handleUploadError');
}
}