2022-06-19 08:16:35 -05:00
|
|
|
import { Socket, io } from 'socket.io-client';
|
2022-07-01 12:00:12 -05:00
|
|
|
import { writable } from 'svelte/store';
|
2022-06-19 08:16:35 -05:00
|
|
|
import { serverEndpoint } from '../constants';
|
|
|
|
|
import type { ImmichAsset } from '../models/immich-asset';
|
|
|
|
|
import { assets } from './assets';
|
|
|
|
|
|
2022-07-01 12:00:12 -05:00
|
|
|
let websocket: Socket;
|
|
|
|
|
|
2022-06-19 08:16:35 -05:00
|
|
|
export const openWebsocketConnection = (accessToken: string) => {
|
2022-06-24 04:18:50 +01:00
|
|
|
const websocketEndpoint = serverEndpoint.replace('/api', '');
|
2022-07-01 12:00:12 -05:00
|
|
|
|
2022-06-24 04:18:50 +01:00
|
|
|
try {
|
2022-07-01 12:00:12 -05:00
|
|
|
websocket = io(websocketEndpoint, {
|
2022-06-24 04:18:50 +01:00
|
|
|
path: '/api/socket.io',
|
|
|
|
|
transports: ['polling'],
|
|
|
|
|
reconnection: true,
|
|
|
|
|
forceNew: true,
|
|
|
|
|
autoConnect: true,
|
|
|
|
|
extraHeaders: {
|
|
|
|
|
Authorization: 'Bearer ' + accessToken,
|
|
|
|
|
},
|
|
|
|
|
});
|
2022-06-19 08:16:35 -05:00
|
|
|
|
2022-06-24 04:18:50 +01:00
|
|
|
listenToEvent(websocket);
|
|
|
|
|
} catch (e) {
|
|
|
|
|
console.log('Cannot connect to websocket ', e);
|
|
|
|
|
}
|
2022-06-19 08:16:35 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const listenToEvent = (socket: Socket) => {
|
|
|
|
|
socket.on('on_upload_success', (data) => {
|
|
|
|
|
const newUploadedAsset: ImmichAsset = JSON.parse(data);
|
2022-07-01 12:00:12 -05:00
|
|
|
// assets.update((assets) => [...assets, newUploadedAsset]);
|
2022-06-19 08:16:35 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
socket.on('error', (e) => {
|
|
|
|
|
console.log('Websocket Error', e);
|
|
|
|
|
});
|
|
|
|
|
};
|
2022-07-01 12:00:12 -05:00
|
|
|
|
|
|
|
|
export const closeWebsocketConnection = () => {
|
|
|
|
|
websocket?.close();
|
|
|
|
|
};
|