|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { useQuery } from "@tanstack/react-query"; |
| 4 | +import { getLatestRelease } from "../services/github"; |
| 5 | +import { env } from "@/env.mjs"; |
| 6 | +import { useEffect, useState } from "react"; |
| 7 | + |
| 8 | +const DISMISS_KEY = "portabase-update-dismissed"; |
| 9 | +const DISMISS_DURATION = 1000 * 60 * 60 * 24; |
| 10 | + |
| 11 | +export const useUpdateCheck = () => { |
| 12 | + const [isDismissed, setIsDismissed] = useState(true); |
| 13 | + |
| 14 | + const { data: latestRelease, isLoading } = useQuery({ |
| 15 | + queryKey: ["latest-release", env.NEXT_PUBLIC_UPDATE_CHANNEL], |
| 16 | + queryFn: () => getLatestRelease(env.NEXT_PUBLIC_UPDATE_CHANNEL as any), |
| 17 | + staleTime: 1000 * 60 * 60, |
| 18 | + }); |
| 19 | + |
| 20 | + const currentVersion = env.NEXT_PUBLIC_PROJECT_VERSION; |
| 21 | + |
| 22 | + useEffect(() => { |
| 23 | + if (!latestRelease) return; |
| 24 | + |
| 25 | + const latestVersion = latestRelease.tag_name.replace(/^v/, ""); |
| 26 | + const cleanCurrentVersion = currentVersion?.replace(/^v/, ""); |
| 27 | + |
| 28 | + if (latestVersion && cleanCurrentVersion && latestVersion !== cleanCurrentVersion) { |
| 29 | + const dismissedData = localStorage.getItem(DISMISS_KEY); |
| 30 | + if (dismissedData) { |
| 31 | + const { version, timestamp } = JSON.parse(dismissedData); |
| 32 | + const now = Date.now(); |
| 33 | + if (version === latestRelease.tag_name && now - timestamp < DISMISS_DURATION) { |
| 34 | + setIsDismissed(true); |
| 35 | + return; |
| 36 | + } |
| 37 | + } |
| 38 | + setIsDismissed(false); |
| 39 | + } else { |
| 40 | + setIsDismissed(true); |
| 41 | + } |
| 42 | + }, [latestRelease, currentVersion]); |
| 43 | + |
| 44 | + const dismissUpdate = () => { |
| 45 | + if (latestRelease) { |
| 46 | + localStorage.setItem(DISMISS_KEY, JSON.stringify({ |
| 47 | + version: latestRelease.tag_name, |
| 48 | + timestamp: Date.now() |
| 49 | + })); |
| 50 | + setIsDismissed(true); |
| 51 | + } |
| 52 | + }; |
| 53 | + |
| 54 | + return { |
| 55 | + latestRelease, |
| 56 | + isLoading, |
| 57 | + isUpdateAvailable: !isDismissed && latestRelease, |
| 58 | + dismissUpdate |
| 59 | + }; |
| 60 | +}; |
0 commit comments