@@ -4,16 +4,51 @@ import { userSyncService } from "@follow/store/user/store"
44import { tracker } from "@follow/tracker"
55import { clearStorage } from "@follow/utils/ns"
66import type { FetchError } from "ofetch"
7+ import { useEffect } from "react"
78
89import { setLoginModalShow } from "~/atoms/user"
910import { QUERY_PERSIST_KEY } from "~/constants"
1011import { useAuthQuery } from "~/hooks/common"
11- import { deleteUserCustom as deleteUserFn , getAccountInfo , signOut as signOutFn } from "~/lib/auth"
12+ import {
13+ deleteUserCustom as deleteUserFn ,
14+ getAccountInfo ,
15+ getSession as refreshBetterAuthSession ,
16+ signOut as signOutFn ,
17+ } from "~/lib/auth"
1218import { ipcServices } from "~/lib/client"
1319import { clearAuthSessionToken , getAuthSessionToken } from "~/lib/client-session"
1420import { defineQuery } from "~/lib/defineQuery"
1521import { clearLocalPersistStoreData } from "~/store/utils/clear"
1622
23+ const sessionCookieRefreshInterval = 1000 * 60 * 60 * 12
24+
25+ let lastSessionCookieRefreshAt = 0
26+ let sessionCookieRefreshPromise : Promise < unknown > | null = null
27+
28+ const refreshAuthSessionCookie = async ( ) => {
29+ if ( IN_ELECTRON && ! getAuthSessionToken ( ) ) {
30+ return
31+ }
32+
33+ if ( Date . now ( ) - lastSessionCookieRefreshAt < sessionCookieRefreshInterval ) {
34+ return
35+ }
36+
37+ sessionCookieRefreshPromise ??= refreshBetterAuthSession ( )
38+ . then ( ( result ) => {
39+ if ( ! result ?. error ) {
40+ lastSessionCookieRefreshAt = Date . now ( )
41+ }
42+ return result
43+ } )
44+ . catch ( ( ) => null )
45+ . finally ( ( ) => {
46+ sessionCookieRefreshPromise = null
47+ } )
48+
49+ await sessionCookieRefreshPromise
50+ }
51+
1752export const auth = {
1853 getSession : ( ) => defineQuery ( whoamiQueryKey , ( ) => userSyncService . whoami ( ) ) ,
1954 getAccounts : ( ) => defineQuery ( [ "auth" , "accounts" ] , ( ) => getAccountInfo ( ) ) ,
@@ -92,6 +127,32 @@ export const useSession = (options?: { enabled?: boolean }) => {
92127 } as const
93128}
94129
130+ export const useAuthSessionCookieRefresh = ( enabled : boolean ) => {
131+ useEffect ( ( ) => {
132+ if ( ! enabled ) {
133+ return
134+ }
135+
136+ const refresh = ( ) => {
137+ if ( document . visibilityState !== "hidden" ) {
138+ void refreshAuthSessionCookie ( )
139+ }
140+ }
141+
142+ refresh ( )
143+
144+ const interval = window . setInterval ( refresh , sessionCookieRefreshInterval )
145+ window . addEventListener ( "focus" , refresh )
146+ document . addEventListener ( "visibilitychange" , refresh )
147+
148+ return ( ) => {
149+ window . clearInterval ( interval )
150+ window . removeEventListener ( "focus" , refresh )
151+ document . removeEventListener ( "visibilitychange" , refresh )
152+ }
153+ } , [ enabled ] )
154+ }
155+
95156export const handleSessionChanges = ( ) => {
96157 setLoginModalShow ( false )
97158 const authSessionToken = getAuthSessionToken ( )
0 commit comments