Skip to content

Commit

Permalink
refactor(web): websocket events (#7152)
Browse files Browse the repository at this point in the history
  • Loading branch information
michelheusschen authored Feb 16, 2024
1 parent bbf7a54 commit c84c0ba
Show file tree
Hide file tree
Showing 10 changed files with 134 additions and 99 deletions.
1 change: 1 addition & 0 deletions web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"devDependencies": {
"@faker-js/faker": "^8.0.0",
"@floating-ui/dom": "^1.5.1",
"@socket.io/component-emitter": "^3.1.0",
"@sveltejs/adapter-static": "^3.0.1",
"@sveltejs/kit": "^2.0.6",
"@sveltejs/vite-plugin-svelte": "^3.0.0",
Expand Down
18 changes: 8 additions & 10 deletions web/src/lib/components/asset-viewer/detail-panel.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { locale } from '$lib/stores/preferences.store';
import { featureFlags } from '$lib/stores/server-config.store';
import { user } from '$lib/stores/user.store';
import { websocketStore } from '$lib/stores/websocket';
import { websocketEvents } from '$lib/stores/websocket';
import { getAssetThumbnailUrl, getPeopleThumbnailUrl, isSharedLink } from '$lib/utils';
import { getAssetFilename } from '$lib/utils/asset-utils';
import { autoGrowHeight } from '$lib/utils/autogrow';
Expand All @@ -30,7 +30,7 @@
mdiPencil,
} from '@mdi/js';
import { DateTime } from 'luxon';
import { createEventDispatcher, onDestroy } from 'svelte';
import { createEventDispatcher, onMount } from 'svelte';
import { slide } from 'svelte/transition';
import { asByteUnitString } from '../../utils/byte-units';
import { handleError } from '../../utils/handle-error';
Expand Down Expand Up @@ -91,14 +91,12 @@
$: people = asset.people || [];
$: showingHiddenPeople = false;
const unsubscribe = websocketStore.onAssetUpdate.subscribe((assetUpdate) => {
if (assetUpdate && assetUpdate.id === asset.id) {
asset = assetUpdate;
}
});
onDestroy(() => {
unsubscribe();
onMount(() => {
return websocketEvents.on('on_asset_update', (assetUpdate) => {
if (assetUpdate.id === asset.id) {
asset = assetUpdate;
}
});
});
const dispatch = createEventDispatcher<{
Expand Down
43 changes: 21 additions & 22 deletions web/src/lib/components/faces-page/person-side-panel.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import LoadingSpinner from '$lib/components/shared-components/loading-spinner.svelte';
import { timeBeforeShowLoadingSpinner } from '$lib/constants';
import { boundingBoxesArray } from '$lib/stores/people.store';
import { websocketStore } from '$lib/stores/websocket';
import { websocketEvents } from '$lib/stores/websocket';
import { getPeopleThumbnailUrl } from '$lib/utils';
import { handleError } from '$lib/utils/handle-error';
import { getPersonNameWithHiddenValue } from '$lib/utils/person';
Expand Down Expand Up @@ -49,32 +49,12 @@
let loaderLoadingDoneTimeout: NodeJS.Timeout;
let automaticRefreshTimeout: NodeJS.Timeout;
const { onPersonThumbnail } = websocketStore;
const dispatch = createEventDispatcher<{
close: void;
refresh: void;
}>();
// Reset value
$onPersonThumbnail = '';
$: {
if ($onPersonThumbnail) {
numberOfAssetFaceGenerated.push($onPersonThumbnail);
if (
isEqual(numberOfAssetFaceGenerated, numberOfPersonToCreate) &&
loaderLoadingDoneTimeout &&
automaticRefreshTimeout &&
selectedPersonToCreate.filter((person) => person !== null).length === numberOfPersonToCreate.length
) {
clearTimeout(loaderLoadingDoneTimeout);
clearTimeout(automaticRefreshTimeout);
dispatch('refresh');
}
}
}
onMount(async () => {
async function loadPeople() {
const timeout = setTimeout(() => (isShowLoadingPeople = true), timeBeforeShowLoadingSpinner);
try {
const { people } = await getAllPeople({ withHidden: true });
Expand All @@ -88,6 +68,25 @@
clearTimeout(timeout);
}
isShowLoadingPeople = false;
}
const onPersonThumbnail = (personId: string) => {
numberOfAssetFaceGenerated.push(personId);
if (
isEqual(numberOfAssetFaceGenerated, numberOfPersonToCreate) &&
loaderLoadingDoneTimeout &&
automaticRefreshTimeout &&
selectedPersonToCreate.filter((person) => person !== null).length === numberOfPersonToCreate.length
) {
clearTimeout(loaderLoadingDoneTimeout);
clearTimeout(automaticRefreshTimeout);
dispatch('refresh');
}
};
onMount(() => {
loadPeople();
return websocketEvents.on('on_person_thumbnail', onPersonThumbnail);
});
const isEqual = (a: string[], b: string[]): boolean => {
Expand Down
17 changes: 10 additions & 7 deletions web/src/lib/components/shared-components/update-panel.svelte
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
<script lang="ts">
import { websocketStore } from '$lib/stores/websocket';
import { websocketEvents } from '$lib/stores/websocket';
import type { AssetStore } from '$lib/stores/assets.store';
import { onMount } from 'svelte';
export let assetStore: AssetStore | null;
websocketStore.onAssetUpdate.subscribe((asset) => {
if (asset && asset.originalFileName && assetStore) {
assetStore.updateAsset(asset, true);
onMount(() => {
return websocketEvents.on('on_asset_update', (asset) => {
if (asset.originalFileName && assetStore) {
assetStore.updateAsset(asset, true);
assetStore.removeAsset(asset.id); // Update timeline
assetStore.addAsset(asset);
}
assetStore.removeAsset(asset.id); // Update timeline
assetStore.addAsset(asset);
}
});
});
</script>
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
let showModal = false;
const { onRelease } = websocketStore;
const { release } = websocketStore;
const semverToName = ({ major, minor, patch }: ServerVersionResponseDto) => `v${major}.${minor}.${patch}`;
$: releaseVersion = $onRelease && semverToName($onRelease.releaseVersion);
$: serverVersion = $onRelease && semverToName($onRelease.serverVersion);
$: $onRelease?.isAvailable && handleRelease();
$: releaseVersion = $release && semverToName($release.releaseVersion);
$: serverVersion = $release && semverToName($release.serverVersion);
$: $release?.isAvailable && handleRelease();
const onAcknowledge = () => {
localStorage.setItem('appVersion', releaseVersion);
Expand Down
22 changes: 7 additions & 15 deletions web/src/lib/stores/assets.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { throttle } from 'lodash-es';
import { DateTime } from 'luxon';
import { writable, type Unsubscriber } from 'svelte/store';
import { handleError } from '../utils/handle-error';
import { websocketStore } from './websocket';
import { websocketEvents } from './websocket';

export enum BucketPosition {
Above = 'above',
Expand Down Expand Up @@ -96,22 +96,14 @@ export class AssetStore {

connect() {
this.unsubscribers.push(
websocketStore.onUploadSuccess.subscribe((value) => {
if (value) {
this.addPendingChanges({ type: 'add', value });
}
websocketEvents.on('on_upload_success', (asset) => {
this.addPendingChanges({ type: 'add', value: asset });
}),

websocketStore.onAssetTrash.subscribe((ids) => {
if (ids) {
this.addPendingChanges(...ids.map((id) => ({ type: 'trash', value: id }) as PendingChange));
}
websocketEvents.on('on_asset_trash', (ids) => {
this.addPendingChanges(...ids.map((id): TrashAsset => ({ type: 'trash', value: id })));
}),

websocketStore.onAssetDelete.subscribe((value) => {
if (value) {
this.addPendingChanges({ type: 'delete', value });
}
websocketEvents.on('on_asset_delete', (id: string) => {
this.addPendingChanges({ type: 'delete', value: id });
}),
);
}
Expand Down
70 changes: 33 additions & 37 deletions web/src/lib/stores/websocket.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createEventEmitter } from '$lib/utils/eventemitter';
import type { AssetResponseDto, ServerVersionResponseDto } from '@immich/sdk';
import { io, type Socket } from 'socket.io-client';
import { get, writable } from 'svelte/store';
import { loadConfig } from './server-config.store';
import { user } from './user.store';

export interface ReleaseEvent {
Expand All @@ -10,58 +10,54 @@ export interface ReleaseEvent {
serverVersion: ServerVersionResponseDto;
releaseVersion: ServerVersionResponseDto;
}
export interface Events {
on_upload_success: (asset: AssetResponseDto) => void;
on_asset_delete: (assetId: string) => void;
on_asset_trash: (assetIds: string[]) => void;
on_asset_update: (asset: AssetResponseDto) => void;
on_asset_hidden: (assetId: string) => void;
on_asset_restore: (assetIds: string[]) => void;
on_person_thumbnail: (personId: string) => void;
on_server_version: (serverVersion: ServerVersionResponseDto) => void;
on_config_update: () => void;
on_new_release: (newRelase: ReleaseEvent) => void;
}

const websocket: Socket<Events> = io('', {
path: '/api/socket.io',
transports: ['websocket'],
reconnection: true,
forceNew: true,
autoConnect: false,
});

export const websocketStore = {
onUploadSuccess: writable<AssetResponseDto>(),
onAssetDelete: writable<string>(),
onAssetTrash: writable<string[]>(),
onAssetUpdate: writable<AssetResponseDto>(),
onPersonThumbnail: writable<string>(),
serverVersion: writable<ServerVersionResponseDto>(),
connected: writable<boolean>(false),
onRelease: writable<ReleaseEvent>(),
serverVersion: writable<ServerVersionResponseDto>(),
release: writable<ReleaseEvent>(),
};

let websocket: Socket | null = null;
export const websocketEvents = createEventEmitter(websocket);

websocket
.on('connect', () => websocketStore.connected.set(true))
.on('disconnect', () => websocketStore.connected.set(false))
.on('on_server_version', (serverVersion) => websocketStore.serverVersion.set(serverVersion))
.on('on_new_release', (releaseVersion) => websocketStore.release.set(releaseVersion))
.on('connect_error', (e) => console.log('Websocket Connect Error', e));

export const openWebsocketConnection = async () => {
try {
if (websocket) {
return;
}

if (!get(user)) {
return;
}

websocket = io('', {
path: '/api/socket.io',
transports: ['websocket'],
reconnection: true,
forceNew: true,
autoConnect: true,
});

websocket
.on('connect', () => websocketStore.connected.set(true))
.on('disconnect', () => websocketStore.connected.set(false))
// .on('on_upload_success', (data) => websocketStore.onUploadSuccess.set(data))
.on('on_asset_delete', (data) => websocketStore.onAssetDelete.set(data))
.on('on_asset_trash', (data) => websocketStore.onAssetTrash.set(data))
.on('on_asset_update', (data) => websocketStore.onAssetUpdate.set(data))
.on('on_person_thumbnail', (data) => websocketStore.onPersonThumbnail.set(data))
.on('on_server_version', (data) => websocketStore.serverVersion.set(data))
.on('on_config_update', () => loadConfig())
.on('on_new_release', (data) => websocketStore.onRelease.set(data))
.on('error', (e) => console.log('Websocket Error', e));
websocket.connect();
} catch (error) {
console.log('Cannot connect to websocket', error);
}
};

export const closeWebsocketConnection = () => {
if (websocket) {
websocket.close();
}
websocket = null;
websocket.disconnect();
};
42 changes: 42 additions & 0 deletions web/src/lib/utils/eventemitter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type {
DefaultEventsMap,
EventsMap,
ReservedOrUserEventNames,
ReservedOrUserListener,
} from '@socket.io/component-emitter';
import type { Socket } from 'socket.io-client';

export function createEventEmitter<
ListenEvents extends EventsMap = DefaultEventsMap,
EmitEvents extends EventsMap = ListenEvents,
ReservedEvents extends EventsMap = NonNullable<unknown>,
>(socket: Socket<ListenEvents, EmitEvents>) {
function on<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(
ev: Ev,
listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>,
) {
socket.on(ev, listener);
return () => {
socket.off(ev, listener);
};
}

function once<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(
ev: Ev,
listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>,
) {
socket.once(ev, listener);
return () => {
socket.off(ev, listener);
};
}

function off<Ev extends ReservedOrUserEventNames<ReservedEvents, ListenEvents>>(
ev: Ev,
listener: ReservedOrUserListener<ReservedEvents, ListenEvents, Ev>,
) {
socket.off(ev, listener);
}

return { on, once, off };
}
11 changes: 7 additions & 4 deletions web/src/routes/(user)/people/[personId]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import { createAssetInteractionStore } from '$lib/stores/asset-interaction.store';
import { assetViewingStore } from '$lib/stores/asset-viewing.store';
import { AssetStore } from '$lib/stores/assets.store';
import { websocketStore } from '$lib/stores/websocket';
import { websocketEvents } from '$lib/stores/websocket';
import { getPeopleThumbnailUrl } from '$lib/utils';
import { clickOutside } from '$lib/utils/click-outside';
import { handleError } from '$lib/utils/handle-error';
Expand Down Expand Up @@ -68,7 +68,6 @@
});
const assetInteractionStore = createAssetInteractionStore();
const { selectedAssets, isMultiSelectState } = assetInteractionStore;
const { onPersonThumbnail } = websocketStore;
let viewMode: ViewMode = ViewMode.VIEW_ASSETS;
let isEditingName = false;
Expand Down Expand Up @@ -119,8 +118,6 @@
$: isAllArchive = [...$selectedAssets].every((asset) => asset.isArchived);
$: isAllFavorite = [...$selectedAssets].every((asset) => asset.isFavorite);
$: $onPersonThumbnail === data.person.id &&
(thumbnailData = getPeopleThumbnailUrl(data.person.id) + `?now=${Date.now()}`);
$: {
if (people) {
Expand All @@ -138,6 +135,12 @@
if (action == 'merge') {
viewMode = ViewMode.MERGE_PEOPLE;
}
return websocketEvents.on('on_person_thumbnail', (personId: string) => {
if (data.person.id === personId) {
thumbnailData = getPeopleThumbnailUrl(data.person.id) + `?now=${Date.now()}`;
}
});
});
const handleKeyboardPress = (event: KeyboardEvent) => {
Expand Down

0 comments on commit c84c0ba

Please sign in to comment.