Files
pleno-vue/src/components/global/VersionCheck.vue
T

99 lines
2.8 KiB
Vue

<script setup lang="ts">
import { onMounted, ref, computed } from "vue";
import Swal from "sweetalert2";
import { SessionUser } from "@/components/session/token/SessionUser.vue";
const VITE_COMMIT_HASH = import.meta.env.VITE_COMMIT_HASH || 'No commit hash';
const VITE_IS_DEV = import.meta.env.DEV || false;
/**
* Variables
*/
const localVersion = VITE_COMMIT_HASH;
const localStorageLastCheckKey = "lastVersionCheck";
const versionCheckUrl = "/worker/version";
const versionCheckDelay = 1000 * 60 * 5; // 5 minutes
const latestVersion = ref<string | null>(null);
const lastVersionCheck = ref(localStorage.getItem(localStorageLastCheckKey) ? parseInt(localStorage.getItem(localStorageLastCheckKey) || "0") : 0);
/**
* Computed
*/
const currentVersion = computed(() => localVersion || "unknown");
const isUpdateAvailable = computed(() => {
return latestVersion.value !== null && latestVersion.value !== currentVersion.value;
});
const shouldCheckForUpdate = computed(() => {
// In dev mode, do not check for updates
if (VITE_IS_DEV) {
return false;
}
// If never checked before, should check
if (lastVersionCheck.value === 0) {
return true;
}
// If enough time has passed since last check, should check
const now = Date.now();
return (now - lastVersionCheck.value) > versionCheckDelay;
});
/**
* Methods
*/
const showUpdateAvailableNotification = () => {
Swal.fire({
title: 'Opdatering tilgængelig',
text: `En ny version (${latestVersion.value}) er tilgængelig! Du bruger i øjeblikket version ${currentVersion.value}. Opdater venligst siden for at få den nyeste version.`,
icon: 'info',
confirmButtonText: 'Opdater nu',
}).then((result) => {
if (result.isConfirmed) {
window.location.reload();
}
});
}
const checkForUpdate = async () => {
const response = await SessionUser.request(
versionCheckUrl,
'GET',
);
// Verify response
if (!response || !response.data || !response.data.data || !response.data.data.version) {
console.error("Invalid version check response:", response);
return;
}
// Update last check time
lastVersionCheck.value = Date.now();
localStorage.setItem(localStorageLastCheckKey, lastVersionCheck.value.toString());
// Update latest version
latestVersion.value = response.data.data.version;
// Notify user if update is available
if (isUpdateAvailable.value) {
showUpdateAvailableNotification();
}
return response;
}
/**
* Lifecycle Hooks
*/
onMounted(() => {
if (shouldCheckForUpdate.value) {
checkForUpdate();
}
window.addEventListener('focus', () => {
if (shouldCheckForUpdate.value) {
checkForUpdate();
}
});
window.setInterval(() => {
if (shouldCheckForUpdate.value) {
checkForUpdate();
}
}, versionCheckDelay);
});
</script>
<template>
</template>
<style scoped>
</style>