Skip to content

Commit 25445dd

Browse files
authored
[Fix] Use hrtime for game closed playtime (#915)
* use hrtime for game closed playtime * fix bigint math * rm logs
1 parent ce59211 commit 25445dd

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

src/backend/main.ts

+14-6
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,7 @@ import { PROVIDERS } from 'common/types/proxy-types'
184184
import 'backend/ipcHandlers/quests'
185185
import 'backend/ipcHandlers/achievements'
186186
import 'backend/utils/auto_launch'
187+
import { hrtime } from 'process'
187188
import { getHyperPlayReleaseObject } from './storeManagers/hyperplay/utils'
188189

189190
async function startProxyServer() {
@@ -1123,6 +1124,8 @@ ipcMain.handle(
11231124
const { minimizeOnGameLaunch } = GlobalConfig.get().getSettings()
11241125

11251126
const startPlayingDate = new Date()
1127+
// Uses hrtime for monotonic timer not subject to clock drift or sync errors
1128+
const startPlayingTimeMonotonic = hrtime.bigint()
11261129

11271130
if (!tsStore.has(game.app_name)) {
11281131
tsStore.set(
@@ -1272,12 +1275,17 @@ ipcMain.handle(
12721275
// Update playtime and last played date
12731276
const finishedPlayingDate = new Date()
12741277
tsStore.set(`${appName}.lastPlayed`, finishedPlayingDate.toISOString())
1275-
// Playtime of this session in minutes
1276-
const sessionPlaytime =
1277-
(finishedPlayingDate.getTime() - startPlayingDate.getTime()) / 1000 / 60
1278+
// Playtime of this session in minutes. Uses hrtime for monotonic timer not subject to clock drift or sync errors
1279+
const stopPlayingTimeMonotonic = hrtime.bigint()
1280+
const sessionPlaytimeInMs =
1281+
(stopPlayingTimeMonotonic - startPlayingTimeMonotonic) / BigInt(1000000)
1282+
const sessionPlaytimeInMinutes =
1283+
sessionPlaytimeInMs / BigInt(1000) / BigInt(60)
1284+
12781285
const totalPlaytime =
1279-
sessionPlaytime + tsStore.get(`${appName}.totalPlayed`, 0)
1280-
tsStore.set(`${appName}.totalPlayed`, Math.floor(totalPlaytime))
1286+
sessionPlaytimeInMinutes +
1287+
BigInt(tsStore.get(`${appName}.totalPlayed`, 0))
1288+
tsStore.set(`${appName}.totalPlayed`, Number(totalPlaytime))
12811289

12821290
if (runner === 'gog') {
12831291
await updateGOGPlaytime(appName, startPlayingDate, finishedPlayingDate)
@@ -1330,7 +1338,7 @@ ipcMain.handle(
13301338
store_name: getStoreName(runner),
13311339
browserUrl: browserUrl ?? undefined,
13321340
platform: getPlatformName(install.platform!),
1333-
playTimeInMs: sessionPlaytime * 60 * 1000,
1341+
playTimeInMs: Number(sessionPlaytimeInMs),
13341342
platform_arch: install.platform!
13351343
}
13361344
})

0 commit comments

Comments
 (0)